\n\n\n\n My Bot Command Strategy for Telegram & Discord - AI7Bot \n

My Bot Command Strategy for Telegram & Discord

📖 10 min read1,949 wordsUpdated Mar 16, 2026

Hey everyone, Marcus here from ai7bot.com. It’s March 13th, 2026, and I’ve been wrestling with a particular problem lately that I bet many of you building bots have faced or are about to face. I’m talking about managing bot commands and interactions across multiple platforms without losing your mind. Specifically, I’ve been diving deep into Telegram and Discord, trying to figure out how to keep things sane when your bot needs to do similar things in both places.

For a while, my approach was what I’d call “brute force duplication.” If my bot had a /help command on Telegram, I’d write the code for it. Then, if I needed a similar !help command on Discord, I’d pretty much copy-paste and tweak. This worked for a bit, especially when my bots were small and focused. But as they grew, and as I started adding more features, it became a nightmare. Updating one command meant updating two, three, or even more places. Bug fixes? Multiply by the number of platforms. It was slow, error-prone, and frankly, sucked the joy out of building.

I remember one late night, probably fueled by too much coffee and not enough sleep, trying to debug why my Telegram bot’s /status command was showing outdated info while the Discord bot’s !status was perfectly fine. Turned out, I’d updated the data source in one place and completely forgotten about the other. That was my “aha!” moment. There had to be a better way. And that better way, for me, has been leaning heavily into a more unified API-driven approach for core bot logic, abstracting the platform-specific stuff as much as possible.

The Multi-Platform Bot Headache: A Real Pain

Let’s be honest, building a bot for a single platform is challenging enough. You’re dealing with API quirks, rate limits, user expectations, and the general unpredictability of the internet. Add a second, third, or even fourth platform into the mix, and suddenly you’re not just building a bot; you’re building a translation layer, a synchronization engine, and a mental health management system for yourself.

My first bot, “WeatherBot 2000” (original, right?), started on Telegram. It was simple: you typed /weather <city> and it gave you the current conditions. Great! Then a friend asked if I could put it on Discord. “Sure!” I said, confidently. I copied the weather fetching logic, slapped a Discord command wrapper around it, and boom, “WeatherBot 2000” was on Discord too, responding to !weather <city>. Mission accomplished, or so I thought.

Then came the requests: “Can it show a 3-day forecast?” “Can it use Celsius instead of Fahrenheit?” “Can it also tell me the air quality?” Each new feature meant touching code in at least two places. The forecast feature, for example, required changing how I parsed the weather API response and how I formatted the output. Doing this twice, once for Telegram’s Markdown and once for Discord’s slightly different Markdown (or embeds for a nicer look), was tedious. It wasn’t just copy-pasting; it was re-implementing the presentation logic.

Why Separate Concerns? It’s About Sanity.

The core of the issue was that my “business logic” (fetching weather data, processing it) was intertwined with my “presentation logic” (how it looks on Telegram, how it looks on Discord). This is a classic software development problem, and the solution, as I learned the hard way, is to separate these concerns. Think of it like this:

  • Core Logic: This is what your bot does. For WeatherBot, it’s making API calls to a weather service, parsing the JSON response, and extracting relevant data. This part should be platform-agnostic.
  • Platform Adapters/Presentation Logic: This is how your bot talks on each platform. It’s the Telegram API calls, the Discord API calls, handling command prefixes, formatting messages with Markdown or embeds, sending files, etc.

When you keep these separate, you can update your core weather-fetching logic once, and it instantly benefits both your Telegram and Discord bots. If Telegram releases a new fancy message formatting option, you only need to update your Telegram adapter. The weather fetching part remains untouched.

Building a Unified Core with APIs: My “WeatherBrain” Example

After my debugging nightmare, I decided to rebuild “WeatherBot 2000” from the ground up, but this time with a clear separation. I created a small, internal API for my bot’s core functionality. I call it “WeatherBrain” (still working on the names, okay?).

WeatherBrain is just a simple Python Flask application (it could be anything, even a set of functions in a library, but an API makes it easier to scale and test independently). It exposes endpoints like /api/weather?city=london&units=metric and /api/forecast?city=london&days=3. When called, it hits a real external weather API (like OpenWeatherMap or AccuWeather), processes the data, and returns a clean, consistent JSON response.

Here’s a simplified peek at what a WeatherBrain endpoint might look like:


# weather_brain_api.py (simplified Flask example)
from flask import Flask, request, jsonify
import requests
import os

app = Flask(__name__)

# This would ideally be in a config or environment variable
WEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY") 
OPENWEATHER_URL = "http://api.openweathermap.org/data/2.5/weather"

@app.route('/api/weather', methods=['GET'])
def get_current_weather():
 city = request.args.get('city')
 units = request.args.get('units', 'metric') # 'metric' or 'imperial'

 if not city:
 return jsonify({"error": "City parameter is required"}), 400

 params = {
 'q': city,
 'appid': WEATHER_API_KEY,
 'units': units
 }

 try:
 response = requests.get(OPENWEATHER_URL, params=params)
 response.raise_for_status() # Raise an exception for HTTP errors
 data = response.json()

 # Process and simplify the data
 weather_info = {
 "city": data['name'],
 "country": data['sys']['country'],
 "description": data['weather'][0]['description'].capitalize(),
 "temperature": data['main']['temp'],
 "feels_like": data['main']['feels_like'],
 "humidity": data['main']['humidity'],
 "wind_speed": data['wind']['speed']
 }
 return jsonify(weather_info)

 except requests.exceptions.RequestException as e:
 app.logger.error(f"Error fetching weather for {city}: {e}")
 return jsonify({"error": "Could not fetch weather data"}), 500
 except KeyError as e:
 app.logger.error(f"Key error in weather data for {city}: {e}")
 return jsonify({"error": "Unexpected weather data format"}), 500

if __name__ == '__main__':
 app.run(debug=True, port=5001)

Now, both my Telegram bot and my Discord bot don’t talk directly to OpenWeatherMap. They talk to WeatherBrain. This is a huge win! If I want to switch from OpenWeatherMap to AccuWeather, I only change the code in weather_brain_api.py. The bots don’t even know it happened.

Telegram and Discord Bots: Becoming Thin Clients

With WeatherBrain handling the heavy lifting, my actual Telegram and Discord bot code became much simpler. They now act like “thin clients” or “adapters.” Their job is purely to:

  1. Listen for commands (e.g., /weather <city> or !weather <city>).
  2. Parse the command and extract arguments.
  3. Make an HTTP request to WeatherBrain.
  4. Receive the JSON response from WeatherBrain.
  5. Format that JSON response into a platform-specific message.
  6. Send the message back to the user.

Here’s a simplified example of how the Telegram adapter might look:


# telegram_bot.py (simplified)
import telebot
import requests
import os

TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
WEATHER_BRAIN_API_URL = "http://localhost:5001/api/weather" # Or your deployed API URL

bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN)

@bot.message_handler(commands=['weather'])
def send_weather(message):
 try:
 args = message.text.split(maxsplit=1)
 if len(args) < 2:
 bot.reply_to(message, "Please provide a city. E.g., `/weather London`")
 return

 city = args[1]
 
 # Call the internal API
 response = requests.get(WEATHER_BRAIN_API_URL, params={'city': city, 'units': 'metric'})
 response.raise_for_status()
 weather_data = response.json()

 if "error" in weather_data:
 bot.reply_to(message, f"Error: {weather_data['error']}")
 return

 # Format for Telegram
 output = (
 f"*{weather_data['city']}, {weather_data['country']}*\n"
 f"Weather: {weather_data['description']}\n"
 f"Temperature: {weather_data['temperature']:.1f}°C (Feels like {weather_data['feels_like']:.1f}°C)\n"
 f"Humidity: {weather_data['humidity']}%\n"
 f"Wind: {weather_data['wind_speed']:.1f} m/s"
 )
 bot.reply_to(message, output, parse_mode='Markdown')

 except requests.exceptions.RequestException as e:
 bot.reply_to(message, "Sorry, I couldn't fetch the weather right now. My brain seems to be taking a nap.")
 print(f"Error calling WeatherBrain API: {e}")
 except Exception as e:
 bot.reply_to(message, "An unexpected error occurred. Please try again later.")
 print(f"General error in Telegram bot: {e}")

bot.polling()

And the Discord adapter would look very similar, just using the Discord.py library (or whatever you prefer) for handling commands and formatting messages with Discord’s specific syntax (e.g., embeds for richer messages).

The key here is that both bots are fetching the same structured data from WeatherBrain. They just present it differently. This drastically reduces duplicate code and makes feature additions or bug fixes much easier.

Beyond Commands: Webhooks and Events

This API-driven approach isn’t just for commands. What if your bot needs to react to external events? Say you have a monitoring bot that checks a website’s uptime. When the website goes down, your monitoring service can send a webhook to your WeatherBrain (or a separate “NotifierBrain” API). This API then decides which platforms to notify (Telegram, Discord, email, SMS) and what message to send, passing the structured alert data to each platform adapter.

This is where the power really shines. Your central API becomes the single source of truth for your bot’s intelligence, and the platform-specific components are just communication channels.

Actionable Takeaways for Your Next Bot Project

If you’re building a bot, especially one you anticipate expanding to multiple platforms or adding complex features, consider these points:

  1. Isolate Your Core Logic: Before you even touch a platform-specific API, write down (or code out) what your bot fundamentally does. What data does it need? What calculations does it perform? This is your “brain.”
  2. Build an Internal API (Even a Simple One): Whether it’s a Flask app, a FastAPI service, or just a well-organized Python module with clear functions, create a layer that encapsulates your core logic and returns consistent, structured data (JSON is great for this). This makes it testable and reusable.
  3. Treat Platform-Specific Bots as Adapters: Their job is to translate user input into calls to your internal API and then translate the internal API’s responses into messages suitable for that platform. They should be “thin” – minimal logic, maximum communication.
  4. Plan for Error Handling: When you have multiple layers (platform bot -> internal API -> external API), errors can happen at any stage. Ensure each layer gracefully handles failures from the layer below it and provides informative (but not overly technical) feedback to the user.
  5. Consider Deployment: If your internal API is a separate service, you’ll need to deploy it somewhere. Services like Heroku, Render, or even a small VPS can host these microservices. Make sure your platform bots can reach your internal API (e.g., if it’s running locally, they need to be on the same network or accessible via a public URL).
  6. Start Small, Iterate: You don’t need to build a massive microservices architecture from day one. Start with one core function, isolate it, and then build your first platform adapter. As you add more features or platforms, you’ll naturally expand your internal API.

Adopting this approach has saved me countless hours of debugging and allowed me to scale my bots much more effectively. The initial setup might feel like a bit more work, but believe me, the long-term benefits in maintainability, scalability, and frankly, your own sanity, are absolutely worth it. Happy bot building!

🕒 Last updated:  ·  Originally published: March 12, 2026

💬
Written by Jake Chen

Bot developer who has built 50+ chatbots across Discord, Telegram, Slack, and WhatsApp. Specializes in conversational AI and NLP.

Learn more →
Browse Topics: Best Practices | Bot Building | Bot Development | Business | Operations
Scroll to Top