Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

python - How can I handle audio messages in pyTelegramBotAPI?

I'm using pyTelegramBotAPI as framework to create a telegram bot. I'm having some troubles with handle audio messages and I can't understand where I am wrong.

Here my code:

# If user send an audio and it's a private chat
@bot.message_handler(content_types=["audio"])
def react_to_audio(message):
    if message.chat.type == "private":
        bot.reply_to(message, """What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat""")

Can anyone help me?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i don't specifically know well how to use pyTelegramBotAPI because also i got problems i couldn't solve so i abandoned it for python-telegram-bot which is better documented in comparison to pyTelegramBotAPI, has a bigger community, is more actively developed and also have an active Telegram group where you can directly ask for help from other developers using this wrapper.

So if you are interested to change to python-telegram-bot, the code for your bot would look something like this:

from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters

token = "" #Insert your token here


def message_handler(update, context):
    update.message.reply_text("Hello")

def audio_handler(update, context):
    if update.message.chat.type == "private": #Checks if the chat is private
        update.message.reply_text("What a nice sound! I'm not here to listen to some audio, tho. My work is to wish a good night to all members of a group chat")



def main():
    """Start the bot."""
    updater = Updater(token, use_context=True)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher


    # on noncommand i.e message
    # Use this if you want to handle also other messages
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, message_handler))

    dispatcher.add_handler(MessageHandler(Filters.audio & ~Filters.command, audio_handler))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == '__main__':
    main()

Here are also some official examples of bots made with this wrapper and the that you can use to better understand the wrapper, if you want more info regard this feel free to DM me on telegram @Husnainn.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...