从电报频道获取消息 - python

时间:2017-08-27 20:22:24

标签: python python-3.x telegram telegram-bot python-telegram-bot

我想用python开发一个电子邮件机器人。 我不知道getUpdates可以帮助我吗?或者有任何方法可以做到这一点。 我想从电报频道获取消息的信息(文本,图片,链接......)。 我不想在频道内做任何功能(编辑,新帖子......)所以我不必是渠道管理员。 实际上我找到了一个可以做到这一点的机器人(@junction_bot),但我不知道如何!! ?? 我应该使用什么语法? 我试过getUpdates方法,应该有用吗?

2 个答案:

答案 0 :(得分:0)

您的机器人需要获得频道管理员权限才能接收消息,您将获得channel_post更新,而不是message

答案 1 :(得分:0)

网址:https://api.telegram.org/bot<TOKEN>/getUpdates

获取最后一个chat_id和消息的python示例

URL = 'https://api.telegram.org/bot' + token + '/'
global last_update_id
last_update_id = 0

def get_updates():
    url = URL + 'getupdates'
    r = requests.get(url)
    return r.json()

def get_message():
    data = get_updates()

    last_object = data['result'][-1]
    current_update_id = last_object['update_id']

    global last_update_id
    if last_update_id != current_update_id:
        last_update_id = current_update_id

        chat_id = last_object['message']['chat']['id']
        message_text = last_object['message']['text']
        message = {
        'chat_id': chat_id, 
        'text': message_text
                }   
        return message['chat_id'], message['text']
    return '0', '0'

您还可以建立json转储并从updates.json获取数据

def format_json_dump():
    data = get_updates()
    with open('updates.json', 'w+') as file:
        json.dump(data, file, indent = 2, ensure_ascii=False)
相关问题