Sure! Below is the code for a Telegram bot in Python that performs all the functionalities you've described. I'll break down the code into sections for clarity and provide explanations along the way. At the end, I'll include instructions on how to install and run the bot.
Prerequisites
Before you begin, make sure you have the following installed:
- Python 3.7 or higher
python-telegram-bot library
SpeechRecognition library
pydub library (for handling audio files)
googletrans library (for text translation)
diffusers library (for image generation)
torch library (dependency for diffusers)
OpenAI (for better NLP understanding, optional)
requests library (for API calls)
sqlite3 library (built-in, for database handling)
You also need to obtain API keys for:
Installation Instructions
Install the required libraries using pip:
pip install python-telegram-bot==13.15
pip install SpeechRecognition
pip install pydub
pip install googletrans==4.0.0rc1
pip install diffusers
pip install torch
pip install requests
Bot Code
import logging
import sqlite3
import requests
import speech_recognition as sr
from pydub import AudioSegment
from googletrans import Translator
from telegram import Update, InputMediaPhoto
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
CallbackContext,
)
from diffusers import StableDiffusionPipeline
import torch
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Replace 'YOUR_TELEGRAM_BOT_TOKEN' and 'YOUR_OPENWEATHERMAP_API_KEY' with your actual tokens
TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
OPENWEATHER_API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'
# Initialize the translator
translator = Translator()
# Initialize Stable Diffusion Pipeline
device = "cuda" if torch.cuda.is_available() else "cpu"
sd_pipeline = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5"
).to(device)
# Database setup
conn = sqlite3.connect('bot_history.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS history (
user_id INTEGER,
query TEXT,
response TEXT
)
''')
conn.commit()
# Helper functions
def save_interaction(user_id, query, response):
cursor.execute('INSERT INTO history (user_id, query, response) VALUES (?, ?, ?)', (user_id, query, response))
conn.commit()
def get_history(user_id):
cursor.execute('SELECT query, response FROM history WHERE user_id=?', (user_id,))
return cursor.fetchall()
# Command handlers
def start(update: Update, context: CallbackContext):
update.message.reply_text('Hello! I am your assistant bot. How can I help you today?')
def help_command(update: Update, context: CallbackContext):
update.message.reply_text('You can send me voice messages to transcribe and translate, text descriptions to generate images, or ask about the weather in a city.')
def history_command(update: Update, context: CallbackContext):
user_id = update.message.from_user.id
history = get_history(user_id)
if history:
messages = ['Your interaction history:']
for query, response in history:
messages.append(f'You: {query}\nBot: {response}\n')
update.message.reply_text('\n'.join(messages))
else:
update.message.reply_text('No history found.')
# Message handlers
def voice_handler(update: Update, context: CallbackContext):
user_id = update.message.from_user.id
file = context.bot.getFile(update.message.voice.file_id)
file.download('voice_note.ogg')
# Convert OGG to WAV
audio = AudioSegment.from_ogg('voice_note.ogg')
audio.export('voice_note.wav', format='wav')
# Recognize speech
recognizer = sr.Recognizer()
with sr.AudioFile('voice_note.wav') as source:
audio_data = recognizer.record(source)
try:
text_russian = recognizer.recognize_google(audio_data, language='ru-RU')
# Translate to English
translation = translator.translate(text_russian, src='ru', dest='en')
response = f"Recognized Text (Russian): {text_russian}\nTranslated Text (English): {translation.text}"
update.message.reply_text(response)
save_interaction(user_id, 'Voice message', response)
except sr.UnknownValueError:
update.message.reply_text("Sorry, I could not understand the audio.")
except Exception as e:
logger.error(e)
update.message.reply_text("An error occurred while processing your voice message.")
def text_handler(update: Update, context: CallbackContext):
user_id = update.message.from_user.id
text = update.message.text.lower()
if 'weather in' in text:
city = text.split('weather in')[-1].strip()
weather_info = get_weather(city)
update.message.reply_text(weather_info)
save_interaction(user_id, text, weather_info)
elif 'generate image' in text or 'draw' in text:
prompt = text.replace('generate image', '').replace('draw', '').strip()
if prompt:
update.message.reply_text("Generating image, please wait...")
image = generate_image(prompt)
if image:
context.bot.send_photo(chat_id=update.effective_chat.id, photo=image)
save_interaction(user_id, text, 'Sent generated image.')
else:
update.message.reply_text("Failed to generate image.")
else:
update.message.reply_text("Please provide a description to generate an image.")
else:
# General handling or NLP processing can be added here
update.message.reply_text("I'm sorry, I didn't understand that. Please try again or use /help.")
save_interaction(user_id, text, 'Did not understand.')
# Function to get weather data
def get_weather(city):
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_API_KEY}&units=metric'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = f"Weather in {city.title()}:\n" \
f"Temperature: {data['main']['temp']}°C\n" \
f"Weather: {data['weather'][0]['description']}\n" \
f"Humidity: {data['main']['humidity']}%\n" \
f"Wind Speed: {data['wind']['speed']} m/s"
return weather
else:
return "Sorry, I couldn't retrieve the weather information."
# Function to generate image using Stable Diffusion
def generate_image(prompt):
try:
with torch.autocast(device):
image = sd_pipeline(prompt, guidance_scale=7.5).images[0]
image.save('generated_image.png')
return open('generated_image.png', 'rb')
except Exception as e:
logger.error(e)
return None
def main():
# Create the Updater and pass it your bot's token.
updater = Updater(TELEGRAM_BOT_TOKEN)
dispatcher = updater.dispatcher
# Add command handlers
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
dispatcher.add_handler(CommandHandler("history", history_command))
# Add message handlers
dispatcher.add_handler(MessageHandler(Filters.voice, voice_handler))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, text_handler))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process is stopped
updater.idle()
if __name__ == '__main__':
main()
Explanation
The bot performs the following functions:
Speech Recognition and Translation:
- Voice Messages: When the user sends a voice message, the
voice_handler function processes it.
- Downloads the voice message and converts it from OGG to WAV format.
- Uses the
SpeechRecognition library to recognize speech in Russian.
- Translates the recognized text to English using
googletrans.
- Sends both the original and translated text back to the user.
- Saves the interaction in the SQLite database.
Image Generation by Text Description:
- Text Commands: When the user sends a text message containing 'generate image' or 'draw', the bot treats the rest of the message as the image description.
- Uses the Stable Diffusion model via the
diffusers library to generate an image based on the description.
- Sends the generated image back to the user.
- Saves the interaction in the SQLite database.
Integration with External API (Weather):
- Weather Requests: If the user asks for the weather by including 'weather in' followed by a city name, the bot fetches weather data.
- Uses the OpenWeatherMap API to get current weather information.
- Formats and sends the weather information back to the user.
- Saves the interaction in the SQLite database.
Interaction History:
- Database: All interactions are saved in an SQLite database with the user's Telegram ID, query, and response.
- History Command: Users can retrieve their interaction history using the
/history command.
Instructions to Run the Bot
-
Clone or Download the Bot Code: Save the code in a file named telegram_bot.py.
-
Install Python and Required Libraries: Make sure you have Python 3.7 or higher installed. Install the required libraries using pip:
pip install python-telegram-bot==13.15
pip install SpeechRecognition
pip install pydub
pip install googletrans==4.0.0rc1
pip install diffusers
pip install torch
pip install requests
-
Obtain API Keys:
- Telegram Bot Token: Create a new bot using BotFather on Telegram and get the bot token.
- OpenWeatherMap API Key: Sign up at OpenWeatherMap and get an API key.
-
Update the Code with Your API Keys:
Replace 'YOUR_TELEGRAM_BOT_TOKEN' and 'YOUR_OPENWEATHERMAP_API_KEY' in the code with your actual tokens.
TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
OPENWEATHER_API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY'
-
Run the Bot:
python telegram_bot.py
-
Start Using the Bot:
- Open Telegram and search for your bot using its username.
- Start a conversation and test the features:
- Send a voice message in Russian to receive the transcription and translation.
- Send text like "Generate image of a sunset over mountains" to get an AI-generated image.
- Ask "Weather in London" to get the current weather.
- Use
/history to view your interaction history.
Additional Notes
-
NLP Integration: For advanced natural language understanding, you can integrate OpenAI's GPT models by installing the openai library and using your API key. This can enhance the bot's ability to understand and process complex queries.
-
User Authorization: You can implement user authentication by maintaining a list of authorized user IDs and checking against it before processing certain commands.
-
Bot Customization: Users can customize bot parameters by implementing additional commands and settings. For example, you could allow users to set their preferred language or units of measurement.
-
Error Handling: The bot includes basic error handling, but you may want to add more comprehensive checks and user feedback mechanisms.
-
Scaling Up: For production use, consider deploying the bot on a server and handling concurrency, perhaps using webhooks instead of polling.
Disclaimer
-
Resource Intensive: Generating images using Stable Diffusion can be resource-intensive and may require a GPU. If running on a local machine without a GPU, this process might be slow.
-
API Limits: Be mindful of the usage limits of the APIs you are using (e.g., OpenWeatherMap has rate limits).
-
Security: Do not expose your API keys in public repositories or share them. Always keep them secure.
Feel free to modify and expand upon this code to suit your specific needs. Happy coding!