简体   繁体   English

Python Telegram bot 太慢了?

[英]Python Telegram bot too slow?

I've just started to make a telegram bot in python, and I've noticed one thing with the small piece of code I did: The bot takes too long to respond.我刚刚开始用 python 制作一个电报机器人,我注意到我所做的一小段代码的一件事:机器人响应时间太长。 Once I send a message to my bot, it takes almost 6-8 seconds to get a reply, which is just too long in a realistic situation.一旦我向我的机器人发送消息,几乎需要 6-8 秒才能得到回复,这在现实情况下太长了。 I'm sure it's not my internet being too slow.我确定这不是我的互联网太慢。 The bot runs from my laptop.机器人从我的笔记本电脑运行。 This is my code:这是我的代码:

from urllib.request import urlopen
import json
import time

token="xxxxxxx:9999999999999999999999999999999"
site="https://api.telegram.org/bot"+token
offset=110000001

while 1:
    time.sleep(0.1)
    content=(urlopen(site+"/getupdates?offset="+str(offset)).read()).decode('utf-8')
    info=json.loads(content)
    if(info['result']):
        incoming=info['result'][0]['message']['text']
        print(incoming)
        if(incoming=='Hi'):
            msg=(urlopen(site+"/sendmessage?chat_id=184044173&text=HI THERE").read()).decode('utf-8')
        offset=info['result'][0]['update_id']+1

What causes this problem and how can I solve this?是什么导致了这个问题,我该如何解决这个问题? I would like to continue using python to make the bot, and I also want to make one from scratch so please don't tell me to use an existing framework or switch languages.我想继续使用python来制作机器人,我也想从头开始制作,所以请不要告诉我使用现有框架或切换语言。

I've heard of 'webhooks' a lot, but never really understood them.我听说过很多“网络钩子”,但从未真正理解它们。 If it is relevant to the solution of this problem please explain webhooks and how to use them with python in detail.如果它与此问题的解决方案相关,请详细解释 webhooks 以及如何将它们与 python 一起使用。

Thanks.谢谢。

I try to explain Webhook for you:我试着为你解释一下 Webhook:

Webhook is the script on your server. Webhook 是您服务器上的脚本。 You tell telegram, use this script for posting any messages.您告诉电报,使用此脚本发布任何消息。

After setwebhook calling telegram will send all messages to your script via POST.在 setwebhook 调用电报后,将通过 POST 将所有消息发送到您的脚本。 And you just need to processing messages that income to webhook.并且您只需要处理收入到 webhook 的消息。

I was write webhook on php, maybe some lines of php code will help you with understending webhooks concept:我在 php 上写了 webhook,也许有些 php 代码会帮助你理解 webhooks 的概念:

$update_json = file_get_contents('php://input');
$update = json_decode($update_json, true);
// get variable;
$chatId = $update["message"]["chat"]["id"];
$userId = $update["message"]["from"]["id"];
$message = $update["message"]["text"];

In first line I read all data (telegram using only post to send messages) next I get message form user, chatId and userId.在第一行中,我读取了所有数据(电报仅使用 post 发送消息),然后我从 user、chatId 和 userId 中获取消息。

next you can use it to send new messages接下来你可以用它来发送新消息

The problem with your code is there is no timeout period for your getUpdates method.您的代码的问题是您的getUpdates方法没有timeout期限。 Try setting a timeout of 10 seconds so that the urlopen will wait 10 seconds for a new update before sending another request.尝试将timeout设置为 10 秒,以便urlopen在发送另一个请求之前等待 10 秒的新更新。

Below is the edited code.下面是编辑后的代码。

from urllib.request import urlopen
import json
import time

token="xxxxxxx:9999999999999999999999999999999"
site="https://api.telegram.org/bot"+token
offset=110000001

while 1:
    time.sleep(0.1)
    content=(urlopen(site+"/getupdates?timeout=10&offset="+str(offset)).read()).decode('utf-8')
    info=json.loads(content)
    if(info['result']):
        incoming=info['result'][0]['message']['text']
        print(incoming)
        if(incoming=='Hi'):
            msg=(urlopen(site+"/sendmessage?chat_id=184044173&text=HI THERE").read()).decode('utf-8')
        offset=info['result'][0]['update_id']+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM