代码之家  ›  专栏  ›  技术社区  ›  Joe

向电报组发送消息,无需用户输入

  •  8
  • Joe  · 技术社区  · 7 年前

    我正在尝试构建一个bot,每当使用python更新最新新闻时,它会自动发送消息。下面是我所做的。

    companies = {
        "name_1": {
            "rss": "name_1 rss link",
            "link": "name_1 link"
        }
    }
    
    import feedparser as fp
    import time, telebot
    token = <TOKEN>
    bot = telebot.TeleBot(token)
    LIMIT = 1
    while True:
        def get_news():
            count = 1
            news = []
            for company, value in companies.items():
                count = 1
                if 'rss' in value:
                    d = fp.parse(value['rss'])
                    for entry in d.entries:
                        if hasattr(entry, 'published'):
                            if count > LIMIT:
                                break
                            news.append(entry.link)
                            count = count + 1
    
            return (news)
        val = get_news()
        time.sleep(10)
        val2 = get_news()
        try:
            if val[0]!=val2[0]:
                bot.send_message(chat_id= "Hardcoded chat_id", text=val2[0])
        except Exception:
            pass
    

    如何更新代码,以便bot将最新新闻发布到添加到的所有组? 我通过以下方式获得chat\u id: bot.get_updates()[-1].message.chat.id 有没有关于如何实现自动化的建议?

    2 回复  |  直到 7 年前
        1
  •  8
  •   576i    7 年前

    使用python telegram bot api,可以发送如下消息

    bot.send_message(id, text='Message')
    

    你需要“机器人”和“id”

    我将它们保存在一个名为“mybots”的字典中,当人们第一次与bot交互或稍后与bot通信时,我会填充/更新该字典。可以对这本词典进行酸洗以保持其持久性。

    mybots = {}
    
    def start(bot, update):
        """Send a message when the command /start is issued."""
          mybots[update.message.chat_id] = bot
          update.message.reply_text('Hello{}!'.format(
               update.effective_chat.first_name))
    
    def send_later():
        for id, bot in mybots.items():
            bot.send_message(id, text='Beep!')
    
        2
  •  4
  •   Sumithran    5 年前

    简而言之,您可以使用 sendMessage() 向特定组或用户发送消息。

    bot.sendMessage(chat_id=chat_id, text=msg)
    

    完整的代码,

    import telegram
    
    
    #token that can be generated talking with @BotFather on telegram
    my_token = ''
    
    def send(msg, chat_id, token=my_token):
        """
        Send a message to a telegram user or group specified on chatId
        chat_id must be a number!
        """
        bot = telegram.Bot(token=token)
        bot.sendMessage(chat_id=chat_id, text=msg)