首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TeleBot如何使用bot.polling和其他函数

TeleBot如何使用bot.polling和其他函数
EN

Stack Overflow用户
提问于 2022-02-10 12:46:02
回答 2查看 1.1K关注 0票数 0

当我使用bot.polling()时,timed_messages永远不会被调用,是否有一种方法可以让这个东西工作,这样我就可以查找发送的消息并发送一个定时的自动消息

代码语言:javascript
复制
import telebot
import cryptocompare
from datetime import datetime

API_KEY = ""
bot = telebot.TeleBot(API_KEY)

@bot.message_handler(regexp="bitcoin")
def bitcoin(message):
    price = cryptocompare.get_price('BTC', 'USD')
    bot.reply_to(message, price['BTC']['USD'])

def timed_messages(prices, current_time):
    if current_time == "9:00:00":
        bot.send_message(-1001236909935, "Good Morning (9:00): \n" + prices)
    if current_time == "12:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (12:00): \n" + prices)
    if current_time == "15:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (15:00): \n" + prices)
    if current_time == "18:00:00":
        bot.send_message(-1001236909935, "Good Evening (18:00): \n" + prices)
    if current_time == "00:00:00":
        bot.send_message(-1001236909935, "Good Night (00:00): \n" + prices)

if __name__ == '__main__':
    while True:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
        timed_messages(prices, current_time)
        bot.polling()
EN

回答 2

Stack Overflow用户

发布于 2022-02-10 17:26:08

您可以使用asyncio来实现您想要的结果。

先进口

代码语言:javascript
复制
import asyncio

然后像这样修改代码:

代码语言:javascript
复制
async def timed_messages_worker():
    while True:
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
            timed_messages(prices, current_time)
            await asyncio.sleep(1)

            
asyncio.create_task(timed_messages_worker)          
asyncio.get_event_loop().run_until_complete(bot.polling())
票数 1
EN

Stack Overflow用户

发布于 2022-04-10 17:31:19

您需要将异步telebot的异步版本结合使用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71065355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档