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
Related
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
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,
)
So, I'am building a discord bot for my private server with python. I want it to reply to a message when a specific message is written for example a person would write "Hi!" and the bot would respond "Hi!". I tried the code #bot.event async def on_message(Hi!): await message.send("Hello!") but it doesn't work. The error is "name 'bot' is not defined". Can any of you help? Here is my whole code NOTE: IT'S IN LITHUANIAN LANGUAGE AND IT'S AMONG US THEMED
```import discord
import random
from discord.ext import commands
from random import choice
client = commands.Bot(command_prefix = '/', help_command=None)
status = ['Žudau crewmates', 'Apsimetinėju :eyes:', 'Prižiūriu https://discord.gg/FNsBtsA']
#client.event
async def on_ready():
print('Imposteris pasiruošęs.')
#client.command()
async def komandos(ctx):
await ctx.send(f'/ping - parodo jūsų interneto greitį, /patarimas - botas duoda patarimą Among Us žaidimui, /meme - Duoda kokį nors among us meme.')
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command()
async def patarimas(ctx):
choices = ["Jei nori būti imposter, pasirink orandžinę spalvą. Ši spalva turi netgi 15.48% tapti imposter. Mažiausiai šansų turintis tėra violetinis. Jis turi tik 3.8%, kad tapti imposter.", "Jei nori kažką nužudyti nueik į admin, susirask tolimiausia nuo electrical, uždaryk savo auką su durimis, išjunk šviesas. Taip gausi kill'ą.", "Jei esi crewmate, niekuo nepasitikėk nebengi žmogus padarė visual task'ą (nesvarbu ar bar pakilo ar ne). Jei esi sus, sakyk, kad turi visual task'ą (jeigu aišku tokį turi).", "Jeigu matai žmogų kuris daro cardswipe, o tu jo neturi, jis bus imposteris. Tai common task'as, jį gali turėti visi arba niekas.", "Pati saugiausia vieta The Skeld žemelapyje yra communications. Ten retai kas užeina. O Polus saugiausia vieta pats startas. Mira HQ saugiausia vieta yra communications "]
ranpatarimas = random.choice(choices)
await ctx.send(ranpatarimas)
#client.command()
async def meme(ctx):
choices = ["https://imgur.com/a/MvYabuk", "https://imgur.com/a/cKEp545", "https://imgur.com/a/5D4XVLl", "https://imgur.com/a/6IioFXt", "https://imgur.com/a/KdVz4WE", "https://imgur.com/a/BlLPvvc", "https://imgur.com/a/aKEMcfO", "https://imgur.com/a/e7Mnu9t", "https://imgur.com/a/sVfVodl", "https://imgur.com/a/F9Zz4A0", "https://imgur.com/a/vbCDxww", "https://imgur.com/a/3K0AHR3"]
ranmeme = random.choice(choices)
await ctx.send(ranmeme)
#bot.event
async def on_message(mirk):
await message.send("NE! Mano mačas dar nesibaigė, o impostorium aš vis dar esu. Palauk prašau kol visus išžudysiu arba bent jau kai būsiu išvoteintas :slight_frown:)")
client.run(<TOKEN>)```
This is a simple code just to get the idea.
#bot.event
async def on_message(message):
if message.author == bot.user: # skip bot messages
return
# write all possible words in lower case.
if message.content.lower() in ['hey', 'hi', 'hello']:
await message.channel.send('Hello!')
await bot.process_commands(message) # to allow other commands
Refrance but not for a bot instead a client it is the same.
Your current solution will respond to every message sent to your server or to your bot dm's, no matter what's the content of it. You can simply check for it.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == 'hi!':
await message.channel.send('Hi there')
await client.process_commands(message)
And change your token, now
Reference:
message
EDIT:
Answering your comment, here's how to check if any word is in the message content
if any(word in message.content.lower() for word in ['hi', 'hello!']):
await message.channel.send('Hi there')
# or
if message.content.lower().startswith(['hi', 'hello!']):
await message.channel.send('Hi there')
I'm coding 10 discord bots for fun, all of these have the same code, (but different token) how can I run all bots with 1 code? Thank you.
import random
import time
import discord
from discord.ext import commands
messaggio = "ti sto dando fastidio?"
client = client = commands.Bot(command_prefix = "()")
Client = discord.Client()
#client.event
async def on_ready():
print("Sono online e pronto ad infastidire")
#client.command() #Invia messaggi in privato ad un utente taggato.
async def infastidisci(ctx, member : discord.Member, numero_di_messaggi = 1):
for x in range(numero_di_messaggi):
y = random.uniform(0.25, 1.50)
time.sleep(y)
print(f"Messaggio inviato a {member}. Messaggi restanti: ", numero_di_messaggi - x - 1)
await member.send(messaggio)
#client.command()
async def infastidisci_chat(ctx, numero_di_messaggi = 1):
for x in range(numero_di_messaggi):
messaggio_fastidioso = "#everyone vi sto dando fastidio?"
canali = ctx.message.guild.text_channels
y = random.uniform(0.25, 1.50)
time.sleep(y)
for canale in canali:
await canale.send(messaggio_fastidioso)
print(f"Messaggio inviato in {canale}. Messaggi restanti: {numero_di_messaggi - x -1}")
client.run(token)
One method:
You retrieve the token from an environment variable:
import os
token = os.environ.get("TOKEN", None)
You execute your program from command line with:
TOKEN=mytoken python3 main.py
What changed here is you have to define the environment variable TOKEN.
Now you can just execute the process multiple time. You can also wrap it in a single command line
TOKEN=mytoken1 python3 main.py & TOKEN=mytoken2 python3 main.py
Not sure if its the lack of coffee, but I'm having a slight issue with uploading random images.
#client.command(aliases=['cuddle'])
async def _cuddle(ctx, *, user):
image= [
'file_1.gif',
'file_2.gif',
'file_3.gif',
'file_4.gif',
'file_5.gif',
'file_6.gif',
'file_7.gif']
await ctx.send(f'You got a Cuddle from{ctx.message.author.mention}, {user}!\n {random.choice(file =discord.file(image))}')
its mostly the
{random.choice(file =discord.file(image))}
ive tryed
discord.file'file_1.gif', method but with no prevail.
I've solved it for anyone who wants to know
import os
#commands.command(aliases=['image'])
async def images(self, ctx):
image = os.listdir('./cogs/image/')
imgString = random.choice(image) # Selects a random element from the list
path = "./cogs/image/" + imgString
await ctx.send(file=discord.File(path))