Installed aiogram version 20.0.4. Python - version 3.10.4. Wrote the echo of the bot for telegrams, when the bot is allowed to /start, it is silent. Where is the mistake ?
`import logging
from aiogram import Bot, Dispatcher, executor, types
API_TOKEN = '...'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
await message.reply("Hi!\nI'm EchoBot!\nPowered by
aiogram.")
#dp.message_handler()
async def echo(message: types.Message):
await message.answer(message.text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)`
Related
import logging
from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.dispatcher.webhook import SendMessage
from aiogram.utils.executor import start_webhook
API_TOKEN = ''
# webhook settings
WEBHOOK_HOST = 'https://xxxxx211.eu.ngrok.io'
WEBHOOK_PATH = ''
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
# webserver settings
WEBAPP_HOST = 'localhost' # or ip
WEBAPP_PORT = 5000
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
dp.middleware.setup(LoggingMiddleware())
#dp.message_handler()
async def echo(message: types.Message):
# Regular request
# await bot.send_message(message.chat.id, message.text)
# or reply INTO webhook
return SendMessage(message.chat.id, message.text)
async def on_startup(dp):
await bot.set_webhook(WEBHOOK_URL.format(token=API_TOKEN))
with bot.with_token("token"):
await bot.set_webhook(WEBHOOK_URL.format(token="token"))
with bot.with_token("token2"):
await bot.set_webhook(WEBHOOK_URL.format(token="token2"))
async def on_shutdown(dp):
logging.warning('Shutting down..')
# insert code here to run it before shutdown
# Remove webhook (not acceptable in some cases)
await bot.delete_webhook()
with bot.with_token("token"):
await bot.delete_webhook()
with bot.with_token("token2"):
await bot.delete_webhook()
# Close DB connection (if used)
await dp.storage.close()
await dp.storage.wait_closed()
logging.warning('Bye!')
if __name__ == '__main__':
start_webhook(
dispatcher=dp,
webhook_path=WEBHOOK_PATH,
on_startup=on_startup,
on_shutdown=on_shutdown,
host=WEBAPP_HOST,
port=WEBAPP_PORT,
)
Here I took the code for multibot from the FAQ aiogram gabbhack repository But there is a problem with the Dispatcher there is a concept
Major token and minor
Because of this, when sending code using await message.answer and the like on the aiogram dock using the second bot, the answer comes to the first bot
And the problem is solved with the help of return SendMessage but this is not an option because 2 requests or more cannot be sent and asynchrony is lost
How can I make it so that the Dispatcher is for each token separately (tokens in an unlimited number)
So that you can turn to #dp and await message.answer and the answer comes to this very bot
I use aiogram. Logic of my bot is very simple - he receive messages from user and send echo-message after 10 seconds. This is a test bot, but in general, I want to make a bot for buying movies with very big database of users. So, my bot must be able to process messages from many users simultaneously and must receive messages using Webhooks. Here are two python scripts:
Telegram-bot on Long Polling:
import asyncio
import logging
from aiogram import Bot, Dispatcher, executor, types
from bot_files.config import *
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=bot_token)
dp = Dispatcher(bot)
#dp.message_handler()
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Telegram-bot on Webhooks:
import asyncio
import logging
from aiogram import Bot, Dispatcher, executor, types
from bot_files.config import *
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=bot_token)
dp = Dispatcher(bot)
WEBHOOK_HOST = f'https://7417-176-8-60-184.ngrok.io'
WEBHOOK_PATH = f'/webhook/{bot_token}'
WEBHOOK_URL = f'{WEBHOOK_HOST}{WEBHOOK_PATH}'
# webserver settings
WEBAPP_HOST = '0.0.0.0'
WEBAPP_PORT = os.getenv('PORT', default=5000)
async def on_startup(dispatcher):
await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True)
async def on_shutdown(dispatcher):
await bot.delete_webhook()
#dp.message_handler()
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
if __name__ == '__main__':
executor.start_webhook(
dispatcher=dp,
webhook_path=WEBHOOK_PATH,
skip_updates=True,
on_startup=on_startup,
on_shutdown=on_shutdown,
host=WEBAPP_HOST,
port=WEBAPP_PORT
)
In the first case, if two users send messages simultaneously, both of messages are processed also simultaneously(acynchrony) - 10 seconds. In the second case messages are processed linearly(not asynchrony) - one of two users must wait 20 seconds. Why telegram-bot on Python with Webhooks can't process messages from many users simultaneously unlike a bot with Long Polling?
Actually telegram-bot on Python with Webhooks can process messages from many users simultaneously. You need just to put #dp.async_task after handler
#dp.message_handler()
#dp.async_task
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
I have a problem in my code.
this is my admin code :
import discord
class Admin(discord.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
#discord.command(name='clear', description='Permet de purger les messages du chat textuel.')
async def clear(self, ctx:discord.ApplicationContext, amount):
await ctx.channel.purge(limit=int(amount))
if __name__ == "__main__":
import main
this is my main code :
# Import discord libs
import discord
from discord.ext import commands
# Import addon libs
import random
import asyncio
# Import extra libs
from libs import settings
# Import Cogs
import admin
client = commands.Bot(command_prefix=" ", help_command=None, intents=discord.Intents.default())
client.add_cog(admin.Admin(client))
#client.event
async def on_ready():
print(f"logged in as {client.user}")
print("Bot is ready!")
await client.change_presence(status=discord.Status.online)
async def changepresence():
await client.wait_until_ready()
statuses = settings.BotStatus
while not client.is_closed():
status = random.choice(statuses)
await client.change_presence(activity=discord.Game(name=status))
await asyncio.sleep(10)
client.loop.create_task(changepresence())
client.run(settings.TOKEN)
this is my console in Visual studio code :
when i use my command /clear amount: he result this error :
but the command /clear amount: working perfectly :D
Can you help me to fix this please :D ?
You need to have the bot respond to the interaction: interaction.response.send_message("message")
Trying to connect Dialogflow to telegram bot to use it with webhook, to avoid using .json file credentials.
A part of code from bot.py
from aiogram.dispatcher.webhook import SendMessage
API_HOST = os.getenv("API_HOST")
BOT_TOKEN = os.getenv("BOT_TOKEN")
APP_NAME = os.getenv("APP_NAME")
WEBHOOK_HOST = f"https://{APP_NAME}.herokuapp.com"
WEBHOOK_PATH = f"/webhook/{BOT_TOKEN}"
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
WEBAPP_HOST = "0.0.0.0"
WEBAPP_PORT = int(os.environ.get("PORT", "5000"))
logging.basicConfig(level=logging.INFO)
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot, storage=MemoryStorage())
async def scheduler():
"""Scheduler for sending messages."""
# aioschedule.every(10).seconds.do(prepare_message)
# keep in mind that this is remote server time
aioschedule.every().day.at("17:00").do(prepare_message)
while True:
await aioschedule.run_pending()
await asyncio.sleep(1)
async def on_startup(dispatcher):
"""Startup function."""
# add commands to MENU button
await set_commands(bot)
asyncio.create_task(scheduler())
if not DEVELOP:
await bot.set_webhook(url=WEBHOOK_URL)
async def on_shutdown(dispatcher):
"""Shutdown function."""
await bot.delete_webhook()
#dp.message_handler(content_types=["text"])
async def reply_to_user(message: types.Message):
# this code should reply to user with data from a webhook, but I do not khow how to retrieve it
return SendMessage(message.chat.id, message.text)
if __name__ == "__main__":
if DEVELOP:
executor.start_polling(dispatcher=dp, skip_updates=True, on_startup=on_startup)
else:
executor.start_webhook(
dispatcher=dp,
webhook_path=WEBHOOK_PATH,
on_startup=on_startup,
on_shutdown=on_shutdown,
skip_updates=True,
host=WEBAPP_HOST,
port=WEBAPP_PORT,
)
Bot hosted on Heroku, it works, but but I do not khow how to retrieve payload from webhook url. Aiogram docs tells to use from aiogram.dispatcher.webhook import SendMessage and nothing more.
I am making a Discord bot with Python.
I would like to add a feature in where, there is a channel called "chatbot", and any text typed there would be replied to by Cleverbot
I am currently trying with the cleverbotfree library, but it doesn't work and I can't find good documentation on it. My problem is that I am trying to run this async command:
#CleverbotAsync.connect
async def async_chat(bot, message, user_input, bot_prompt):
"""Example code using cleverbotfree async API with decorator."""
reply = await bot.single_exchange(user_input)
await message.channel.send(f'{0}'.format(reply))
await bot.close()
However, I can't do this in on_message, because it needs to be run in this snippet of code:
if chnl == 'chatbot':
#whatever running that command
So, I'm not sure how do it.
And yes, I have looked into and tried Selenuim, but it appears that whenever I click the accept button, nothing loads. (This must be a way for Cleverbot to make people actually pay for their API, which I can't do).
Here is my full code(I know it's not the best):
import discord
from discord import channel
from discord.flags import MessageFlags
from webserver import keep_alive
import os
from discord.ext import commands
import youtube_dl
import time
import asyncio
from cleverbotfree import CleverbotAsync
from cleverbotfree import Cleverbot
requests = []
def send(message,user_input,bot_prompt):
asyncio.run(async_chat(message,user_input,'Cleverbot:'))
client = commands.Bot(command_prefix="!")
#client.command()
async def request(ctx, request: str,member: discord.Member):
requests.append('{0}: {1}'.format(member,request))
await ctx.send(f'Thanks {member.metion} for the request, my dev will (hopefully) get right to work!')
#client.command(description="See what my dev is working on")
async def workingon(ctx):
ctx.send("My Dev is currently working on adding a feature in where, in a channel called 'chatbot', it will respond like a human.(though he has spent hours on it, it still doesn't work)")
#client.event
async def on_ready():
#confirming login
print('Logged on as {0.user}'.format(client))
#client.event
async def on_member_join(member):
print(f'Greetings {member}, welcome to server')
#CleverbotAsync.connect
async def async_chat(bot, message, user_input, bot_prompt):
"""Example code using cleverbotfree async api with decorator."""
reply = await bot.single_exchange(user_input)
await message.channel.send(f'{0}'.format(reply))
await bot.close()
#client.event
async def on_message(message):
#getting variables
usrnm = str(message.author).split('#')[0]
msg = str(message.content)
chnl = str(message.channel.name)
if usrnm != str(client.user).split('#')[0] and msg.lower() == 'hello bot':
await message.channel.send(f'Hello {usrnm}, how do you do?')
return
if str(msg).split(' ')[0].lower() == 'im':
print(str(msg).split(' ')[0].lower())
await message.channel.send(f'Hi, {msg}, im a dad!')
if msg.lower() == '!newfeatures':
await message.channel.send(f'{message.author.mention}, The newest feature added to the bot is that if a new member joins, it will greet them')
if msg.lower() == '!help':
await message.channel.send(f'{message.author.mention}, Type !help for help. \n\n - Typing "Hello Bot" will make the bot answer\n - typing "im" before anything will make the bot answer\n - Typing !newfeatures will tell you the newest feature added to the bot.')
if chnl == 'chatbot':
send(message,str(message.content),'Cleverbot:')
#muting system
keep_alive()
TOKEN = os.environ.get("DISCORD_BOT_SECRET")
client.run(TOKEN)
Any help would be appreciated!