python - 当另一个命令已经在 python-telegram-bot 中运行时,有什么方法可以运行一个命令?
问题描述
假设在 start 函数中有一个无限循环。当它运行时......我需要另一个命令在后台运行。另一个功能。(例如停止命令)我尝试将它放在“updater.start_polling()”之后,但由于一些原因它没有工作。我无法为此设置调度程序。
def start(update: Update, context: CallbackContext) -> None:
while true:
context.bot.send_message(chat_id=update.effective_chat.id, text= "Choose an option. ('/option1' , '/option 2', '/...')")
def main():
updater = Updater("<MY-BOT-TOKEN>", use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
解决方案
利用线程
from time import sleep
from threading import Thread
def start(update: Update, context: CallbackContext) -> None:
while true:
context.bot.send_message(chat_id=update.effective_chat.id, text= "Choose an option. ('/option1' , '/option 2', '/...')")
sleep(.1)
def stop():
pass # some code here
def main():
updater = Updater("<MY-BOT-TOKEN>", use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
t1 = Thread(target=updater.start_polling)
t2 = Thread(target=stop)
t1.start()
t2.start()
updater.idle()
if __name__ == '__main__':
main()
推荐阅读
- react-native - 同时使用 AVFoundation 和 RNCamera 预览
- python-3.x - 将 tkinter 变量保存到 txt 文件错误
- go - 使用未从包中导出的类型
- c++ - 释放 PyBind11 中的 GIL 以在 Python 中使用 OpenMP 进行多线程
- localization - Web 应用程序全球化/本地化工具的选项?
- java - 我可以使用通过 ajax 传递的值来使用准备好的语句进行数据库搜索吗?
- python - 尝试解析电子邮件的 html 时,“不能在像对象这样的字节上使用字符串模式”
- recaptcha - 在没有 php 的情况下在 Github 页面上实现 recaptcha?
- docker-compose - docker-compose down 不会..“关闭”容器
- haskell - 为以 char 开头的字符串创建一个布尔值以返回 true,而后续值可以是 char 数字或下划线