Python和humans的Telegram bot库
tebot的Python项目详细描述
TeBot-Python和humans的Telegram bot库
目标是保持简单。在
演示(有时可能不起作用):@demo_tebot
如何安装
pip3 install tebot
如何使用
启动bot
如果您的项目使用neotasker
^{pr2}$如果没有:
fromneotaskerimporttask_supervisorfromtebotimportTeBottask_supervisor.create_aloop('default',default=True)task_supervisor.start()mybot=TeBot(delay=2)mybot.set_token('botsecrettoken')mybot.start()
(有关详细信息,请参阅neotasker文档)
停止机器人
mybot.stop()# if your project doesn't use neotaskertask_supervisor.stop()# optionally - save bot statewithopen('bot-state.json','w')asfh:fh.write(json.dumps(mybot.serialize()))
发送消息
# textmybot.send(text='hello world',chat_id=chat_id)# fileswithopen('image.jpg','rb')asfh:mybot.send(media=fh.read(),chat_id=chat_id)
如果从处理程序发送消息,并且未指定chat_id, 使用当前聊天ID:
@mybot.route(path='/start')defstart(**kwargs):mybot.send('bot started')
下载文件
defsomehandler(**kwargs):payload=kwargs.get('payload')if'document'inpayload:try:content=mybot.get_file_content(payload['document'].get('file_id'))# process file contentexcept:# unable to download file
高级API:routes
TeBot有烧瓶式路由,可以通过调用
mybot.register_route(fn,path,methods)
或者使用函数修饰符:
# message handler. can be only one, registered to handle all regular messages@mybot.route(methods='message')defmy_message(chat_id,text,**kwargs):# some code# command handler for /start and /help@mybot.route(path=['/start','/help'])defstart(**kwargs):mybot.send('got HELP command')# command and callback query handler@mybot.route(methods='*')defdefault_cmd_handler(path,**kwargs):mybot.send(f'command not implemented: {path}')
路由参数
- 在
path命令路径,可以是多个命令的字符串或列表/元组
在 - 在
methods可以是字符串或列表/元组。有效值为: “消息”、“命令”(如果未指定方法,则为默认值)和 “查询”/“回拨查询”。如果指定了“*”,则为注册该方法 命令和回调查询
在
处理程序kwargs
将以下kwarg发送到已注册的处理程序:
- 在
text消息文本(仅适用于消息处理程序)
在 - 在
path命令路径(例如“/select”for“/select*from data”)
在 - 在
query_string命令查询字符串(例如上面的“*from data”) 示例)
在 - 在
chat_id当前聊天id
在 - 在
query_id回调查询id,如果处理程序作为回调查询执行 经办人
在 - 在
payload完整请求负载
在 - 在
method回调查询的“command”或“query”
在
处理程序返回数据
- 在
如果处理了命令,则处理程序可能不返回任何内容
在 - 在
如果处理了回调查询,则处理程序可能返回dict,它用作 回调查询答案的有效负载(例如,包括“url”、“show_alert”等, 详见电报机器人API)
在
低级API:处理程序
重写类方法:
- 在
handle_message处理常规消息
在 - 在
handle_命令处理命令(启动 带“/”)
在 - 在
handle\u query处理回调查询
在 - 在
on_message重写以实现高级消息处理
在 - 在
on_query重写以实现高级回调查询处理
在
机器人程序选项
mybot.timeout=5# set Telegram API timeout (default: 10 sec)mybot.retry_interval=1# if API command fails, re-send it in 1 second# (default: None, don't re-send)
腹板挂钩
要使用web hooks,init bot object,,但不要启动它。使用 process_update(payload)处理webhook有效负载的方法。在
TeBot没有自己的web服务器模块,你可以使用任何可用的。在
要注册webhook,请使用set_webhookbot对象方法(参数与 对于https://core.telegram.org/bots/api#setwebhook)
要删除webhook,请使用delete\uwebhookbot对象方法(不需要参数)。在
其他的一切
有关更多信息,请参阅函数pydoc。在
- 项目
标签: