Send messages to telegram group without user input
Asked Answered
C

2

9

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?

Convertible answered 10/3, 2018 at 22:57 Comment(1)
Your code could improve in readability if you didn't indent so deeply (7 levels! ...use functions to break chunks out) Linus said this: news.ycombinator.com/item?id=3414637Penniepenniless
F
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!')
Funkhouser answered 14/4, 2018 at 21:49 Comment(0)
D
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)
Desiccant answered 26/12, 2018 at 16:58 Comment(2)
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"Sludge
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 thisDesiccant

© 2022 - 2024 — McMap. All rights reserved.