I need to make my server to respond immediately and equally to a large number of bots and at the same time and not become heavily loaded as happens with polling. Requests that users will make in @qwerty1_bot and @qwerty2_bot will be processed in the same way, all the functionality and the database are all the same, it’s some kind of mirrors. The bot’s code is very large and originally worked on an asynchronous telebot and contained code that was responsible for answering users like this:
@bot.message_handler(commands=['start'])
async def send_welcome(message):
await bot.reply_to(message, 'Hello world!')
therefore, remaking it for something else is not an option at all, it will take too much time, so I asked ChatGPT for help to achieve this with minimal changes, and after my minor edits the bot script looked like this:
from flask import Flask, request, abort
import telebot
from telebot.async_telebot import AsyncTeleBot
import asyncio
import ipaddress
app = Flask(__name__)
ALLOWED_IP_RANGES = [
ipaddress.ip_network('149.154.160.0/20'),
ipaddress.ip_network('91.108.4.0/22')
]
def is_ip_allowed(ip):
ip = ipaddress.ip_address(ip)
print(any(ip in network for network in ALLOWED_IP_RANGES))
return any(ip in network for network in ALLOWED_IP_RANGES)
async def process_message(bot_token, update):
bot = AsyncTeleBot(bot_token, parse_mode=None)
@bot.message_handler(commands=['start'])
async def send_welcome(message):
await bot.reply_to(message, 'Hello world!')
print('something sended')
await bot.process_new_updates([telebot.types.Update.de_json(update)])
@app.route('/webhook/<bot_token>', methods=['POST'])
async def webhook(bot_token):
if not is_ip_allowed(request.remote_addr):
abort(403)
if request.headers.get('content-type') == 'application/json':
update = request.get_json()
asyncio.create_task(process_message(bot_token, update))
return '', 200
else:
abort(403)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=443, ssl_context=('webhook_cert.pem', 'webhook_pkey.pem'))
Everything seems to be fine, the request comes, my webhook returns success to the telegram servers, “something sent” appears in the console, but… the bot doesn’t respond to me as a user in the telegram itself. What should I do?
Thanks in advance!
NoNoty is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.