8

I'm trying to build a bot which automatically sends a message whenever there is an update in the latest news using python. Following is what I did.

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

How can I update my code so that the bot publishes the latest news to all the groups to which it is added? I got the chat_id using: bot.get_updates()[-1].message.chat.id Any suggestions on how to automate this?

Joe
  • 291
  • 1
  • 3
  • 18
  • Your code could improve in readability if you didn't indent so deeply (7 levels! ...use functions to break chunks out) Linus said this: https://news.ycombinator.com/item?id=3414637 – JohnGH Dec 05 '19 at 21:08

2 Answers2

8

Using the python-telegram-bot api, you can send a message like this

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

you need the "bot" and "id"

I keep these in a dictionary called "mybots" which I fill/update when people interact with the bot for the first time / or on later communication with the bot. It's possible to pickle this dictionary to keep it persistant.

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!')
576i
  • 7,579
  • 12
  • 55
  • 92
5

In short, you can use sendMessage() to send message to a specific group or user.

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

the complete code,

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)
Sumithran
  • 6,217
  • 4
  • 40
  • 54
  • 1
    In my case the group is "prueba". Where do I have to include the group name in the code? This code send the msg to the bot (but nobody can see it, just me) but not to the group named "prueba" – kamome Jul 19 '19 at 19:02
  • 1
    hi @kamome, you dont have to add your group name in the code, instead you have to add the chat_id in the code. if you are having trouble in finding the chat_id id of a specific group, please [refer this](https://stackoverflow.com/q/32423837/6562458) – Sumithran Jul 19 '19 at 19:28