Created
September 11, 2023 08:10
-
-
Save vlad-ds/b0d449a591a03a605e6c63fb85eff171 to your computer and use it in GitHub Desktop.
Telegram Bot Template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from dotenv import load_dotenv | |
from telegram import Update | |
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters | |
load_dotenv() | |
TOKEN = os.environ["BOT_TOKEN"] | |
def start_polling(): | |
# Create the Application and pass it the token | |
application = Application.builder().token(TOKEN).build() | |
# on different commands - answer in Telegram | |
application.add_handler(CommandHandler("start", start)) | |
# on text message | |
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text_message)) | |
# on voice message | |
application.add_handler(MessageHandler(filters.VOICE, handle_voice_message)) | |
# run the bot | |
application.run_polling() | |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | |
await update.message.reply_markdown(f'''Welcome! | |
''') | |
async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | |
chat_id = str(update.effective_chat.id) | |
message = update.message.text | |
translation = translate(message, language) | |
await update.message.reply_text(translation, reply_to_message_id=update.message.message_id) | |
async def handle_voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: | |
chat_id = str(update.effective_chat.id) | |
voice = update.message.voice | |
voice_file = await voice.get_file() | |
if not os.path.exists("voice_messages"): | |
os.makedirs("voice_messages") | |
# download user's voice message | |
voice_file_path = f"voice_messages/{voice_file.file_id}.oga" | |
await voice_file.download_to_drive(custom_path=voice_file_path) | |
# transcribe user's message to English | |
transcript = translate_whisper(voice_file_path) | |
# translate the transcript to the target language | |
await update.message.reply_text(transcript, reply_to_message_id=update.message.message_id) | |
# delete the voice file | |
os.remove(voice_file) | |
def main(): | |
start_polling() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment