我用python-telegram-bot制作了一个电报机器人。我已经为机器人定义了一个单词列表,我想管理组中的聊天机器人。也就是说,如果在定义的列表中找到聊天中的单词,则机器人将删除它。我将机器人添加到一个组并在那里管理它。机器人应该控制发送给组的消息,如果消息中有一个单词在mlist上,机器人应该删除该消息。我的代码:
# -*- coding: cp1256 -*-
#!/usr/bin/python
import os, sys
from telegram.ext import Filters
from telegram.ext import Updater, MessageHandler
import re
def delete_method(bot, update):
if not update.message.text:
print("it does not contain text")
return
mlist=['Hello', 'سلام']
for i in mlist:
if re.search(i, update.message.text):
bot.delete_message(chat_id=update.message.chat_id,message_id=update.message.message_id)
def main():
updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.all, delete_method))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
# -*- coding: utf8 -*-
#!python2
import time
import json
import requests
#TOKEN = XXXXXX
URL = "https://api.telegram.org/bot{}/".format(TOKEN)
def get_updates(offset=None):
url = URL + "getUpdates?timeout=100"
if offset:url += "&offset={}".format(offset)
return requests.get(url).json()
def get_last_update_id(updates):
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
return max(update_ids)
def delete_message(message_id, chat_id,msg):
mlist=['Hello', 'سلام']
url=URL + "deleteMessage?message_id={}&chat_id={}".format(message_id, chat_id)
for i in mlist:
if i in msg:request.get(url)
def echo_all(updates):
for update in updates["result"]:
cid = update["message"]["chat"]["id"]
msg = update["message"].get("text")
mid = update["message"].get("message_id")
if msg:delete_message(mid,cid,msg)
def main():
last_update_id = None
while True:
try:
updates = get_updates(last_update_id)
z=updates.get("result")
if z and len(z) > 0:
last_update_id = get_last_update_id(updates) + 1
echo_all(updates)
time.sleep(0.5)
except Exception as e:
print(e)
if __name__ == '__main__':
main()