我正在尝试构建一个机器人,当使用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
如何更新我的代码,以便机器人将最新消息发布到添加它的所有组?
我使用了chat_id:
bot.get_updates()[-1].message.chat.id
关于如何自动化的任何建议?
答案 0 :(得分:1)
使用python-telegram-bot api,您可以发送这样的消息
bot.send_message(id, text='Message')
你需要&#34; bot&#34;和&#34; id&#34;
我将这些保存在一个名为&#34; mybots&#34;当人们第一次与机器人交互时,或者在以后与机器人进行通信时,我填写/更新。可以腌制这本词典以保持它的持久性。
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!')
答案 1 :(得分:0)
简而言之,您可以使用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 mensage to a telegram user specified on chatId
chat_id must be a number!
"""
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id=chat_id, text=msg)