So im using this code and i have from discord_components import * and DiscordComponents(bot) in on_ready. I did pip install --update discord-components. This is the code im using.
#bot.command()
async def button(ctx):
await ctx.channel.send(
"This is a button test :smile:",
components =[
Button(style=ButtonStyle.blue, label ="Button 1"),
Button(style=ButtonStyle.red, label ="Button 2"),
Button(style=ButtonStyle.URL, label ="this is a picture", url="https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg" ),
],
)
component = discord.Component
interaction1 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 1"))
await interaction1.respond(content = "Button 1 Seems like it working")
interaction2 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 2"))
await interaction2.respond(content = "Button 2 Seems like it working")
There is no error message and when I do $button it prints but if I click on a button it says interaction failed(still no error message) I'm new to button so if you could help me that would be great
Related
I'm trying to write a Telegram bot to help a friend with his online buisness.
I'm trying to make an interactive menu, but if I try to use an emoji as a prefix the #bot.message_handler doesn't read the user input, resulting in the menu not updating.
Working code (with "/" as command prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("/Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)
Faulty code (with UNICODE emoji as prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("\U0001F60Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["\U0001F60Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)
You can use regular expression as there is no native way to change the prefixes:
#bot.message_handler(regexp="^\U0001F60H(your_command)")
so currently I try to program a calculator but I hit a roadblock. Well, I watched a tutorial by Glowstik on how to make calculator discord bot but it seems that his code doesn't work anymore. So, can anybody suggest changes that I can make to the code to make the bot work? Thanks in advance.
Here is the code :
import discord
import os
from discord.ext import commands, tasks
from online import keep_alive
from discord_slash import SlashCommand
from itertools import cycle
from discord_components import *
import datetime
client = commands.Bot(command_prefix="!")
slash = SlashCommand(client, sync_commands=True)
status = cycle([
" Unanswered Question of Life", " Self - Referential Paradox",
" Near-infinite density?", " Dark matter ?",
" Measurement of the speed of light in one straight line",
" Schrodinger's cat ???",
"The light side of Discord is the path of many unnatural abilities"
])
#client.event
async def on_ready():
print("I have logged in as {0.user}".format(client))
status_swap.start()
DiscordComponents(client)
buttons = [[
Button(style=ButtonStyle.grey, label='1'),
Button(style=ButtonStyle.grey, label='2'),
Button(style=ButtonStyle.grey, label='3'),
Button(style=ButtonStyle.blue, label='+'),
Button(style=ButtonStyle.red, label='Clear')
],
[
Button(style=ButtonStyle.grey, label='4'),
Button(style=ButtonStyle.grey, label='5'),
Button(style=ButtonStyle.grey, label='6'),
Button(style=ButtonStyle.blue, label='-'),
Button(style=ButtonStyle.red, label='Exit')
],
[
Button(style=ButtonStyle.grey, label='7'),
Button(style=ButtonStyle.grey, label='8'),
Button(style=ButtonStyle.grey, label='9'),
Button(style=ButtonStyle.blue, label='×'),
Button(style=ButtonStyle.red, label='←')
],
[
Button(style=ButtonStyle.grey, label='00'),
Button(style=ButtonStyle.grey, label='0'),
Button(style=ButtonStyle.grey, label='.'),
Button(style=ButtonStyle.blue, label='÷'),
Button(style=ButtonStyle.red, label='=')
]]
def calculator(exp):
o = exp.replace('×', '*')
o = o.replace('÷', '/')
result = " "
try:
result = str(eval(o))
except:
result = "An error occurs"
return result
#client.command()
async def operator(ctx):
m = await ctx.send(content="Loading calculator")
expression = "None"
delta = datetime.datetime.utcnow() + datetime.timedelta(minutes = 5)
e = discord.Embed(title="Basic Operation Calculator",description=expression)
await m.edit(components=buttons, embed=e)
while True :
res = await client.wait_for("button click")
while m.created_at < delta :
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == "None" or expression == 'An error occurs':
expression = ''
elif res.component.label == 'Exit':
await res.respond(content='Calculator Closed. Thanks for using Basic Operation Calculator.',type=7)
break
elif res.component.label == "←":
expression = expression[:-1]
elif res.component.label == 'Clear':
expression = None
elif res.component.label == '=':
expression += calculator(expression)
else:
expression = res.component.label
f = discord.Embed(title='Basic Operation Calculator',description=expression)
await res.respond(content='', embed = f, component=buttons, type=7)
# tasks.loop(minutes=5)
async def status_swap():
await client.change_presence(activity=discord.Game(next(status)))
keep_alive()
client.run(os.getenv('MATH_VAR'))
This code looks like it was taken from https://www.youtube.com/watch?v=3BGcgSm9sv0
which coincidentally I have also used.
Your problem arises from your embed title because it's based around your title having a '|' followed by the user's ID.
try changing the embed title from "Basic Operation Calculator" to f"{ctx.message.author}'s calculator|{ctx.message.author.id}" and tell me if that works. I've modified the code I'm using slightly, so this might be wrong, I'm going off of memory here. If that does work, also try f"Basic Operation Calculator|{ctx.message.author.id}" if you want to keep your title name.
This isn't needed but if you also want to add a sliver of text after the '|', you need to change the split statement in
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
to the '|' and any text (thats not the ID) directly after.
so if I want to add "ID: " after, then the split statement would be "| ID: ". Sorry if this sounds confusing, the way this code works is very specific, and I'm pretty new to Stack Overflow. Let me know if you run into any errors or have any questions. If nothing else works I'm happy to send you my current code I'm using since It's only slightly modified. Next time you post a question, try your best to be as specific as possible with your question.
Hello I recently made a help command using discord_components buttons (I know they arent fully supported by Discord.py) but I still went ahead. The problem is that whenever I run the command and receive the Buttons to click on, they alway say "This Interaction Failed". I can't seem to find what's wrong. Please help.
Thanking You,
NightMX.
import discord
from discord.ext import commands
from discord_components.component import ButtonStyle
from discord_components import DiscordComponents, Button, Select, SelectOption
from discord_components.interaction import InteractionType
class BotCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpv2(self, ctx):
funbutton = Button(style=ButtonStyle.grey, label="Fun Commands", id="funcmds")
monkedevbutton = Button(style=ButtonStyle.grey, label="Attachment Commands", id="monkecmds")
# utilitybutton = Button(style = ButtonStyle.grey, label = "3", id = "embed3")
funembed = discord.Embed(title="Fun Commands", colour=discord.Colour.orange())
funembed.add_field(name="k.joke", value="Sends a Random joke from PyJokes")
monkedevembed = discord.Embed(title="Fun Commands", colour=discord.Colour.blurple())
monkedevembed.add_field(name="k.dog", value="Sends a Random Dog Fact")
monkedevembed.add_field(name="k.monkey", value="Sends a Monkey's Picture")
monkedevembed.add_field(name="k.bird", value="Sends a Bird's Picture")
await ctx.send(
"Kola's Beta Help Command!",
components=[[funbutton, monkedevbutton]]
)
buttons = {
"funcmds": funembed,
"monkedcmds": monkedevembed
}
while True:
event = await self.bot.wait_for('button_click')
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
if response is None:
await event.channel.send(
"Something went Wrong"
)
if event.channel == ctx.channel:
await event.respond(
type=InteractionType.ChannelMessageWithSource, embed=response
)
def setup(client):
client.add_cog(BotCommands(client))
should be content="something" instead of embed = response
i have this aiogram inline buttons
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from middlewares.internationlization import _
choise_sign_select_company = InlineKeyboardMarkup(row_width=1,
inline_keyboard=[
[
InlineKeyboardButton(
text=_('Капитализация ❌'),
callback_data='market_cap_of_company'
),
InlineKeyboardButton(
text=_('Кол-во акций ❌'),
callback_data='count_shares_ofustanding_of_company'
)
],
[
InlineKeyboardButton(
text=_('Цена акции ❌'),
callback_data='current_prise_share_now_of_company'
)
]
])
how to turn these buttons into a check of a button? For example, so that when you click on the "Capitalization ❌" button, the button changes to "Capitalization ✅" (when you click it again, it goes back)
and also the value was stored in the call.data from callback_data
Here comes the keyboard
#dp.message_handler(text='Подобрать компании 🤑')
async def select_sign(message: types.Message):
await message.answer(_('Выберите признаки на которых будет основываться подбор'),
reply_markup=choise_sign_select_company)
await SelectCompanies.enter_the_sign.set()
click on the button is processed here
#dp.callback_query_handler(state=SelectCompanies.enter_the_sign)
async def select_interval(call: types.CallbackQuery):
text = call.data
await call.answer(text)
You can manually implement this feature using callbacks.
For example, store current button`s state in callback and change it after click.
Also, there is aiogram-dialog library. You can find special "checkbox" button there
You can try it:
from aiogram_dialog import DialogManager, ChatEvent
from aiogram_dialog.widgets.kbd import Checkbox, ManagedCheckboxAdapter
from aiogram_dialog.widgets.text import Const
async def check_changed(event: ChatEvent, checkbox: ManagedCheckboxAdapter, manager: DialogManager):
print("Check status changed:", checkbox.is_checked())
check = Checkbox(
Const("✓ Checked"),
Const("Unchecked"),
id="check",
default=True, # so it will be checked by default,
on_state_changed=check_changed,
)
Can somebody help, I cant understand how can I do my bot with two menus.
first - is "short menu" where you press the button and its open "long menu" with all functions
second - in "long menu" menu where I have all functions and the button "Back to Menu".
I cant understnand how to make the button "Back to Menu" that go back me to the "short menu"
help me please. And the Main -- the clicking on buttons should not send a message to the user
def telegram():
with open("madata") as f3:
info = yaml.safe_load(f3)
token = mytoken
bot = Bot(token=token)
dp = Dispatcher(bot)
#greeting message, pin this message in private chat
#dp.message_handler(commands=['start'])
async def greeting(message: types.Message):
chat_id = message.chat.id
msg = '''hello friend'''
# body of keyboard
small_function = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="show functions", callback_data='open menu all functions')
]
],
resize_keyboard=True
)
all_functions = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="function 1", callback_data='do function1')
],
[
KeyboardButton(text="function 2", callback_data='do function2')
],
[
KeyboardButton(text="back to menu", callback_data=' open menu small_function')
],
],
resize_keyboard=True
)
#insert my keyboard
sent_message = await bot.send_message(chat_id=chat_id, text=msg,parse_mode = "Markdown", reply_markup=small_function)
print(sent_message.message_id)
#bot.callback_query_handler(func=lambda call: True)
async def answer(call):