How to make "back" button in aiogram? - python - python

I need to make working "back" button in aiogram that returns to /start menu.
I know what's my mistake is, but I have no idea how to fix it. Can someone help?
back_button = InlineKeyboardButton(text = "back", callback_data="bk")
keyboard_back = InlineKeyboardMarkup().add(back_button)
#dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
return await bot.send_message(message.from_user.id, text="Hello!\nI'm WriteEssayBot!\nI will write any essay for you!", reply_markup = keyboard_inline)
#dp.callback_query_handler()
async def generate_text(call: types.CallbackQuery):
await bot.answer_callback_query(call.id)
if call.data == "bk":
await send_welcome() ```

Related

telegram bot reply message for buttons

recently i created a telegram bot using python and i added keyboard button features to the bot. However, i am having difficulties in getting replies from bot to the buttons users choose.
button7 = KeyboardButton('About Us',request_contact= False)
keyboard2 = ReplyKeyboardMarkup(resize_keyboard = True, one_time_keyboard = True).row(button7)
#dp.message_handler(commands=['info'])
async def mood(message: types.Message):
await message.reply('Do you wish to know about us??', reply_markup=keyboard2)
In this case, i created a button named "About Us" and i want the bot to open a url using webbrowser.open if the user click on that button. Can anyone help me solving this problem?
Try it:
markup = types.InlineKeyboardMarkup()
button1 = types.InlineKeyboardButton(text='Ukraine', url="https://en.wikipedia.org/wiki/Ukraine", callback_data='1')
markup.add(button1)
bot.send_message(message.from_user.id, 'Do you know?, parse_mode='Markdown', reply_markup=markup)
Text (inline button)
from aiogram import Bot, Dispatcher, executor, types
bot = Bot(token='token')
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def welcome(message: types.Message):
markup = types.InlineKeyboardMarkup()
button1 = types.InlineKeyboardButton(text='Ukraine', url="https://en.wikipedia.org/wiki/Ukraine", callback_data='1')
button2 = types.InlineKeyboardButton(text='Hi bot!', callback_data="1")
markup.add(button1, button2)
await bot.send_message(message.from_user.id, "Do you know?", parse_mode="Markdown", reply_markup=markup)
#dp.callback_query_handler(lambda call: True)
async def sendText(call: types.CallbackQuery):
msg = ""
if call.data == "1":
msg = "Hi, programmer!"
await call.message.edit_text(msg)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

Python py-cord / discord.py(2.0.0): Button interaction failed

If I click on my Button everything works as expected, but in Discord is's showing:
This is the Button Code:
# Start Button
start_b = Button(label="Starten", style=discord.ButtonStyle.gray)
async def start_callback(interaction: discord.Interaction):
if not is_server_running():
msg = await interaction.channel.send(embed=discord.Embed(title='START: Starte Server'))
start_server()
await msg.delete()
else:
msg = await interaction.channel.send(embed=discord.Embed(title='Server läuft noch'))
time.sleep(5)
await msg.delete()
start_b.callback = start_callback
...
view.add_item(start_b)
await bot.get_channel(Some ID).send(embed=discord.Embed(title="Dashboard"), view=view)
I guess I have to acknowledge the button interaction somehow.
Is there a way to do this without sending reply messages?
Finally I found it 🥳
You have to add this at the top of your callback:
await interaction.response.defer()
In my example this would be:
# Start Button
start_b = Button(label="Starten", style=discord.ButtonStyle.gray)
async def start_callback(interaction: discord.Interaction):
await interaction.response.defer() # <---- Here
if not is_server_running():
msg = await interaction.channel.send(embed=discord.Embed(title='START: Starte Server'))
start_server()
await msg.delete()
else:
msg = await interaction.channel.send(embed=discord.Embed(title='Server läuft noch'))
time.sleep(5)
await msg.delete()
start_b.callback = start_callback
...
view.add_item(start_b)
await bot.get_channel(Some ID).send(embed=discord.Embed(title="Dashboard"), view=view)

How to have separate interactions for separate buttons | discord.py pycord

How can I have different interactions response on different buttons in pycord/discord.py.
Code:
#client.command()
async def test(ctx: commands.Context):
button = Button(label="Click Below", custom_id="freefire",style=discord.ButtonStyle.green, emoji="<:freefire:944183849779335198>")
button1 = Button(label="Click Below", custom_id="bgmi",style=discord.ButtonStyle.green, emoji="<:bgmi:944184219528208384>")
async def free_fire(interaction: discord.Interaction):
role = ctx.guild.get_role(944152201784336414)
member = ctx.guild.get_member(interaction.user.id)
if role in interaction.user.roles and interaction.custom_id== "freefire":
await interaction.user.remove_roles(role)
await interaction.response.send_message(f"{role} role has been taken from you", ephemeral=True)
else:
await member.add_roles(role)
await interaction.response.send_message(f"{role} role has been given to you", ephemeral=True)
button.callback = free_fire
async def bgmi(interaction: discord.Interaction):
role = ctx.guild.get_role(944152314200088667)
member = ctx.guild.get_member(interaction.user.id)
if role in interaction.user.roles and interaction.custom_id== "bgmi":
await interaction.user.remove_roles(role)
await interaction.response.send_message(f"{role} role has been taken from you", ephemeral=True)
else:
await member.add_roles(role)
await interaction.response.send_message(f"{role} role has been given to you", ephemeral=True)
button.callback = bgmi
It simply gives the role of last button when I click the first button and other buttons do not respond at all there is no error in console or anywhere.
The problem is that you first set button.callback to free_fire, but then you set button.callback to bgmi. This can be solved by changing the second button.callback = ... to button1.callback = ...

Discord.py Buttons - TypeError: string indices must be integers

I am new to discord_components.
I am getting this type error Error screenshot
when i click a button in the message ...
My code is -
#bot.event
async def on_button_click(interaction):
if interaction.component.custom_id == "support_join":
await interaction.respond(content=f"https://discord.gg/xyzabcklmn", ephemeral=True)
elif interaction.component.custom_id == "website_link":
if interaction.member.guild_permission.manage_guild:
await interaction.respond(content=f"https://bot_website/guild/{interaction.guild.id}", ephemeral=True)
Code of buttons -
guild_join_components = [
button(label="Join Support Server", style="3", emoji=smart_bot_emoji, custom_id="support_join"),
button(label="Setup from Website", style="3", emoji=smart_bot_emoji, custom_id="website_link")
]
Code of command -
#bot.command()
async def test(ctx):
await ctx.reply("this is a test cmd", components=guild_join_components)
Please can someone tell that what is this error and how to fix it, do i have a mistake in code or not
If you want more details about this the please comment...
I got something after i searched a lot -
The code should look like -
async def on_button_click(interaction):
if interaction.custom_id == "support_join":
await interaction.respond(content=f"https://discord.gg/xyzabcklmn", ephemeral=True)
elif interaction.custom_id == "website_link":
if interaction.user.guild_permission.manage_guild:
await interaction.respond(content=f"https://bot_website/guild/{interaction.guild.id}", ephemeral=True)
#bot.command()
async def test(ctx):
await ctx.reply("Testing buttons:", components=[[button(label="Join support server", style=1, custom_id="support_join"), button(label="Setup from website", style=1, custom_id="website_link")]])
i = await bot.wait_for("button_click")
await on_button_click(i)

Other user can write -join and then bot will trigger the commend

So I'm making bot in python and I don't know how to make that other user can write -join and then bot will trigger the commend. My code currently is in cogs so I'm using #commands.command instead #bot.command. Here is my code:
class GamesCog(commands.Cog, name="Games"):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def game(self, ctx):
await ctx.send("Find a second person to play dice or play against the bot. (-join/-bot)")
await ctx.send(file=discord.File('game.jpg'))
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["-join", "-bot"]
msg = await self.bot.wait_for("message", check=check)
def setup(bot):
bot.add_cog(GamesCog(bot))
print('File games.py is ready')
I know that in the return msg.author author shouldn't be there, I just don't know what to replace it with.
You're actually doing nothing with the message, you're waiting for it, and then nothing
msg = await self.bot.wait_for("message", check=check)
if msg.content.lower() == "-join":
# Do something
elif msg.content.lower() == "-bot":
# Do something
def check(msg):
return msg.channel == ctx.channel and msg.content.lower() in ["-join", "-bot"]

Categories