Telegram Bot Is Not Working

烂漫一生 提交于 2019-12-11 15:29:11

问题


I made a telegram bot with python-telegram-bot. I have defined a list of words for the bot and I want to manage the chat bot in the group. That is, if there is a word in the chat that is found in the defined list, the bot will delete it. I added the bot to a group and admin it there. The bot should control the messages sent to the group, and if there is a word in the message that is on the mlist, the bot should delete the message. my codes:

# -*- 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()

回答1:


# -*- 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()


来源:https://stackoverflow.com/questions/45660498/telegram-bot-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!