Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

write a python script that get the last message in a telegram group. dont use Telethon…

  1. User

    write a python script that get the last message in a telegram group. dont use Telethon library

  2. Assistant

    To get the last message in a telegram group without using the Telethon library, you can use the python-telegram-bot library. Here is a Python script that does so by implementing a simple Telegram bot:

    import os
    from telegram import Update
    from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
    
    # Replace 'YOUR_TELEGRAM_TOKEN' with the token received from the BotFather on Telegram
    TELEGRAM_TOKEN = 'YOUR_TELEGRAM_TOKEN'
    
    def last_message_handler(update: Update, context: CallbackContext):
        chat_id = update.message.chat_id
        message_text = update.message.text
    
        # Command to get the last message
        if message_text.lower() == '/get_last_message':
            last_msg = update.message.reply_to_message
            if last_msg:
                context.bot.send_message(chat_id=chat_id, text=f'Last message: {last_msg.text}')
            else:
                context.bot.send_message(chat_id=chat_id, text='Reply to a message with "/get_last_message" to get the last message.')
    
    def main():
        # Set up the Updater and Dispatcher
        updater = Updater(TELEGRAM_TOKEN)
        dispatcher = updater.dispatcher
    
        # Add message handler to dispatcher
        dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, last_message_handler))
    
        # Start the bot
        updater.start_polling()
        updater.idle()
    
    
    if __name__ == "__main__":
        main()
    

    To run this script, you will need to install the python-telegram-bot library:

    pip install python-telegram-bot
    

    Replace 'YOUR_TELEGRAM_TOKEN' with the token you received from BotFather when you created your bot on Telegram.

    To use the bot, simply add it to the group and reply to any message with the command /get_last_message. The bot will return the last message in that context. Note that this will only retrieve the most recent message based on the messages replied to and not necessarily the last message of the entire group.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.