#discord-bots
1 messages · Page 348 of 1

you've told discord to call your Interaction stuff "button" and all your Button stuff "interaction"
literally 😭
the button should be only access to the dude who has created the embed how to do it?
like how :3
you have the arguments round the wrong way
look at my example again
fixed
now an other problem, how to check if the user that clicked the button is the one who made the embed?
and how to remove the button after clicking ti?
store a user attribute when creating a class instance and check if interaction.user (user who interacted) is that user
alr
self.remove_item(...) if you're in the view and whatever_you_called_the_view.remove_item(...) for anywhere else
nop it's doesn't get removed!!!!
what doesn't get removed?
did you even specify a thing to be removed?
or did you copy and paste again?
self.remove_item(button)
no, you said an item the button no?
yep
in the:
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green) async def confirm(self, interaction, button):
Correct?
well it's doesn't work
you can use this if you have multi-line code samples:
```py
code
```
it does work
yeah
you need to edit the message after if you want it to show up
also why not just edit the bottom message onto the top message
wdym
because this how it should workl
I need to remove that button ong
but anyway how to do?
you need to edit the message with the view for the changes to show up ```py
class ExampleView(ui.View):
...
async def on_timeout(self):
for item in self.children:
item.disabled = True
await self.message.edit(view = self)```
this is an example using on_timeout which happens when the view expires
remove it and update the view
what is message?
you assign the message beforehand py view = ExampleView(...) view.message = await ctx.reply(your_message_send_thing)
show code
as you asked?
“i want them to be removed” “why are they removed”
:3
so put that code in the button function so when the button gets clicked it’ll run that code?
class Confirm(discord.ui.View):
message = None
def __init__(self, user_id, user_data: user_data_manager, amount_to_float: float):
super().__init__(timeout=None)
self.user_id = user_id
self.user_data = user_data
self.amount_to_float = amount_to_float
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm(self, interaction, button):
if interaction.user.id == self.user_id:
user = self.user_data.get_user(interaction.user.id)
create_embed_coinflip = discord.Embed(
title=":white_check_mark: Coinflip Created",
description=(
":gems: **Gems**: {}\n"
":gems: **New Balance**: {}\n"
":crown~1: **Channel**: <#{}>"
).format(
number_converter.number_to_suffix(self.amount_to_float),
number_converter.number_to_suffix(user.balance - self.amount_to_float),
cfg.FLIP_COIN_CHANNEL_ID),
color=discord.Color.purple())
create_embed_coinflip.set_footer(text=f"{cfg.BOT_NAME} - Coinflip Created")
self.user_data.remove_balance(interaction.user.id, self.amount_to_float)
self.user_data.add_wagered(interaction.user.id, self.amount_to_float)
await interaction.response.send_message(embed=create_embed_coinflip)
self.remove_item(button)
await self.message.edit(embed=create_embed_coinflip, view=self)
else:
await interaction.response.send_message("You can't confirm this.", ephemeral=True)
uh????
help me
Anyone?
also if you are gonna use interactions, use .response.edit_message() or .edit_original_message() if you've already responded to it
and also use guard classes to prevent bulging code
still nothing
[2024-03-29 18:30:07] [ERROR ] discord.ui.view: Ignoring exception in view <Confirm timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Confirm' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 98, in confirm
await interaction.response.send_message(embed=create_embed_coinflip)
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\interactions.py", line 774, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
# don't do this
if ...:
if ...:
if ...:
...
else:
...
else:
...
else:
...
# do this
if not ...:
return
if not ...:
return
if not ...:
return```
await interaction.response.edit_message(view=None)
await interaction.response.send_message(embed=create_embed_coinflip)
read my message
use this instead for code:
```py
code
oke
and reread this @sharp dome
idk what responded means
read the line of code
.response. is a response
it says there
you have responded to the interaction
you cannot respond twice so it'll raise an error if you try that
yea I see it
i need to send 2 message
how to do?
await interaction.response.edit_message(view=None)
await interaction.followup.send(embed=create_embed_coinflip)
like this?, it workin!
at least it correct?
that works to send a new message
editing makes more sense imo but you do you 🤷🏽♂️
yep, it works
@sharp dome do you need any more help? i was going to do an important phone call but i put it off to help you
for now no, go ahead
ngl
thanks for ur help
amazing. congrats on what you did, and you’re welcome for the help
no problem
import discord
from discord.ext import commands
import datetime
welcome_channel = 1221421626202001470
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot("~", intents=intents)
@client.event
async def on_connect():
print("connected")
@client.event
async def on_member_join(member):
channel = client.get_channel(welcome_channel)
embed = discord.Embed(
description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
color=0x000000,
timestamp=datetime.datetime.now(),
)
channel.send(embed=embed)
client.run("")
can anyone explain 2 me y this aint working
its still not sending the message uppon joining
whats the traceback?
any errors?
extra details would be helpful
The error is that you're not awaiting .send()
You're not getting an error because the members intent is also not enabled, so the event won't get triggered at all and your code won't be executed either
where do i need to add where : (
Enable the members intent
Add await on your .send() line
okay lemme try now
help
it still doesnt work
help
[2024-03-29 19:46:50] [ERROR ] discord.ui.view: Ignoring exception in view <CoinFlipButtons timeout=None children=3> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Cancel' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 251, in cancel
await interaction.edit_original_response(view=None)
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\interactions.py", line 487, in edit_original_response
data = await adapter.edit_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
```py
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
async def cancel(self, interaction, button):
coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
if coin_flip is None:
await interaction.response.send_message("Coinflip not found.", ephemeral=True)
return
if coin_flip.started:
await interaction.response.send_message("Coinflip already started.", ephemeral=True)
return
if interaction.user.id == coin_flip.user_id:
coin_flip.cancelled = True
await interaction.edit_original_response(embed=coinflip_embed_battle(self.user_name, coin_flip), view=None)
self.coin_flip.remove_coin_flip(coin_flip.coin_flip_id)
user_data_manager.get_user(interaction.user.id).balance += coin_flip.amount
user_data_manager.add_wagered(interaction.user.id, -coin_flip.amount)
await interaction.followup.send("Coinflip cancelled.", ephemeral=True)
please
@viscid hornet help buddy
whats the issue
the error
idk
I'm dumb
interaction.response.edit_message
this is thje correct
yes
thats for when you HAVEN'T responded to the interaction before
a response is anything with .response.
so you cant do something like this py await interaction.response.defer() await interaction.response.send_message("hello")
interaction.response.defer()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[2024-03-29 20:07:12] [ERROR ] discord.ui.view: Ignoring exception in view <CoinFlipButtons timeout=None children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Call bot' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 288, in call_bot
await self.flip_coin(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 227, in flip_coin
await self.run(interaction)
File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 237, in run
await interaction.response.edit_message(embed=coinflip_embed_battle(self.user_name, coin_flip),
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\interactions.py", line 888, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
```py
@discord.ui.button(label="Call bot", style=discord.ButtonStyle.blurple)
async def call_bot(self, interaction, button):
coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
if not await validate_coin_flip(interaction, coin_flip):
return
if interaction.user.id == coin_flip.user_id:
coinflip_offender = self.bot.user.id
if coin_flip.heads_player == "Undecided":
coin_flip.heads_player = "<@{}>".format(coinflip_offender)
elif coin_flip.tails_player == "Undecided":
coin_flip.tails_player = "<@{}>".format(coinflip_offender)
interaction.response.defer()
await interaction.response.send_message("Bot joined the coinflip.", ephemeral=True)
if coin_flip.heads_player != "Undecided" and coin_flip.tails_player != "Undecided":
await self.flip_coin(interaction)
because the interaction has already been responded to
the flip_coin modify the messages
you havent been reading my messages 😭
(all .response. things need to be awaited btw)
async def flip_coin(self, interaction):
coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
while not coin_flip.ended:
await self.run(interaction)
await asyncio.sleep(1)
async def run(self, interaction):
coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
if coin_flip.seconds > 1:
if not coin_flip.message_has_sent:
coin_flip.started = True
coin_flip.time = f"<t:{int(time.time() + coin_flip.seconds)}:R>"
await interaction.response.edit_message(embed=coinflip_embed_battle(self.user_name, coin_flip),
view=None)
coin_flip.message_has_sent = True
coin_flip.seconds -= 1
else:
coin_flip.flip_coin()
coin_flip.started = False
await interaction.edit_original_response(embed=coinflip_embed_battle(self.user_name, coin_flip), view=None)
coin_flip.ended = True
define_winner(coin_flip)
self.coin_flip.remove_coin_flip(coin_flip.coin_flip_id)
check your dms
alright
Hi
How are you
Boys i want to create discord bot use python
Where should I start?
I will use replit
this is a shit ton of code for something as easy as this: https://paste.pythondiscord.com/KFNQ
first mistake made without even writing code
dont use replit, it'll choke your bot performance and its far easier to just write the code yourself in an IDE like vscode
learning discord.py at https://discord.gg/dpy
Because i use phone
İ dont have pc
😭
oooof
idk how you program without a pc but oh well
you kinda do need a pc for this sort of stuff
tf

hello
how Can i run quart and discord bot thogheter?
import discord
from discord.ext import commands
from config import config as cfg
from game_modes import game_modes_commands
from user import deposit_data_manager
from user import user_commands, user_data_manager as user_data_manager
bot = commands.Bot(command_prefix="$", intents=discord.Intents.default())
deposit_data_manager = deposit_data_manager.DepositManager()
@bot.event
async def on_ready():
user_data_manager.load_users()
print(f"Logged in as {bot.user}")
try:
await bot.add_cog(user_commands.UserCommands(bot, user_data_manager, deposit_data_manager))
await bot.add_cog(game_modes_commands.GameModesCommands(bot, user_data_manager))
except Exception as e:
print(f"Failed to add Balance cog: {e}")
try:
synced = await bot.tree.sync()
print(f"Synced {synced} commands")
except Exception as e:
print(f"Failed to sync commands: {e}")
def run():
bot.run(cfg.TOKEN)
then i have this clas:
import discord
from quart import Quart, request
from config import config as cfg
from user import user_data_manager
from user.deposit_data_manager import DepositManager
quart = Quart(__name__)
async def start_quart():
await quart.run_task(debug=False, port=80, host="0.0.0.0")
class RobloxBot:
def __init__(self, bot, deposit_data_manager: DepositManager, user_data: user_data_manager):
self.bot = bot
self.deposit_data_manager = deposit_data_manager
self.user_data = user_data
@quart.route('/deposit_request', methods=['POST'])
async def deposit_request(self):
data = await request.get_json()
user_id = data['user_id']
code = data['code']
successful_deposit = data['successful_deposit']
deposit = self.deposit_data_manager.get_deposit(user_id)
if deposit is not None:
if deposit.code == code and deposit.successful_deposit:
deposit.successful_deposit = successful_deposit
deposit.balance = data['balance']
deposit.successful_deposit = data['successful_deposit']
user = self.user_data.get_user(user_id)
if user is not None:
user.balance += deposit.balance
user.deposited += deposit.balance
self.user_data.save_users()
self.deposit_data_manager.save_deposits()
return "OK"
async def run_embeds(self):
deposits = self.deposit_data_manager.get_deposits()
while deposits is not None:
for user_id, deposit in deposits.items():
if deposit.successful_deposit:
user = self.user_data.get_user(user_id)
if user is not None:
embed = discord.Embed(
title="Deposit successful",
description=f"Your deposit of {deposit.balance} has been added to your balance",
color=discord.Color.green()
)
channel = self.bot.get_channel(cfg.DEPOSIT_CHANNEL_ID)
await channel.send(embed=embed)
idk how to and even AI doesn't know how to use python
Yo can someone help me? So when I add my bot into a server, it shows the commands of the bot in the server, but the bot isn't in the server?
To run both your Discord bot and Quart web application together, you can utilize Python's asyncio module to manage both asynchronous tasks. You need to create a main function that runs both tasks concurrently.
@sharp dome dmss
need code, I have already tried something like that
Does dpy have support on user install yet?
pretty sure its just an out of sync command tree
like yk when you leave your screen on and showing something for too long
Nah I fixed it
permissions being None?
thats strange
is there a good example on slash commands?
The official example, yes
How do streaming music bots work now days after the Discord Policy change?
erm, i dont think they care about the policy, what changed?
Does anyone know how to put a command behind the pay wall in dpy?
Use checks
@app_commands.command()
async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_link: str):
ids = extract_ids(message_link)
print(ids)
channel_id = ids[1]
print(channel_id)
message_id = ids[2]
print(message_id)
channel = self.bot.get_channel(channel_id)
message = channel.get_message(int(message_id))
await message.add_reaction(emoji)
c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
conn.commit()
await interaction.response.send_message("done",ephemeral=True)
```
How do u add reaction to a message?
is channel_id an int?
Yes it is
However the problem is the get message
channel there is a None type meaning your bot can't find the channel
can you do print(type(channel_id)) see what it prints
My bad it wasn't
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialMessage) from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Changed in version 2.0: `message_id` parameter is now positional-only.
use that instead since all you need is adding a reaction
Anyone have docs on how the SKU works with a dpy bot?
sku?
⚠️ Currently, Premium Apps are available to developers based in the US, UK, and European Union but check back here and in the Discord Developers server for future announcements
Premium Apps are the...
oh
i guess that is in discord.py's master branch
seems like no one did the docs yet because it's new, once you create an SKU the flow of it looks like,
user subscription -> entitlements -> on_entitlement_create, so i would imagine you just have to store that entitlement and check with a command check to see if the user have entitlement, after that you can prompt them with InteractionResponse.require_premium if they dont have it
there are also Bot.create_entitlement to test entitlement triggers based on this doc
The SKU stuff is still a work in progress, and following the discord docs on it isn't very enlightening either, but I think flowerpad nailed it yeah
i repeatedly said to use channel.get_partial_message
okay thank you
# in cog
channel = self.bot.get_channel(channel_id)
message = channel.get_partial_message(message_id)
# message is whatever Message object you want
await message.add_reaction('👍')```
Ty
Will the new polls feature be part of the discordpy?
yes
Is it already and Im just being silly for not looking?
i know its already implemented in disnake dunno about discord.py but for sure will be
DisnakeDev/disnake#1176
Rapptz/discord.py#9759
why none
How are you defining pool? mind sending your main.py code?
self.pool = await aiomysql.create_pool(host='', port=, user='', password='', db='', loop=loop, autocommit=True, maxsize=25)
can anyone help me to create a discord bot
sry but i cant pay anything as i am poor
if you can help pls dm me
channel = self.bot.get_channel(int(cfg.DEPOSIT_CHANNEL_ID))
await channel.send(
f"<@{user.user_id}> has successfully deposited {number_converter.number_to_suffix(deposit.balance)}",
embed=embed)
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1376, in handle_request
return await self.full_dispatch_request(request_context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1414, in full_dispatch_request
result = await self.handle_user_exception(error)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1007, in handle_user_exception
raise error
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1412, in full_dispatch_request
result = await self.dispatch_request(request_context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1506, in dispatch_request
return await self.ensure_async(handler)(**request_.view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\xntro\PycharmProjects\ps99casino\utils\roblox_bot.py", line 50, in deposit_request
await channel.send(
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'```
why???
help
channel is None 🤷
Do you have that code run before the bot is ready? The channel cache will not be ready until then
yes
wait
idk
@naive briar
Why?
class Bot:
def __init__(self, bot: commands.Bot, deposit: DepositManager, user: user_data_manager):
self.bot = bot
self.deposit = deposit
self.user = user
bot = commands.Bot(command_prefix="$", intents=discord.Intents.default())
myclass = Bot(bot)
this is correct?
i dont think theres any option other than regex
Something like:
header_pattern = re.compile(r'^#+\s+.*$', re.MULTILINE)
if header_pattern.match(message.content):
await message.delete()```
Or is there any better way to do it?
.match probably wouldn't work
Try .search instead
!e
import re
print(re.match("^#.*?", "A\n# Something", re.MULTILINE))
print(re.search("^#.*?", "A\n# Something", re.MULTILINE))
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | None
002 | <re.Match object; span=(2, 3), match='#'>
oh yeah match only checks if its at the beginning right?
Yes
i have a text file which contains around 500 lines of different links and i want to send those links at a 5 min interval to one of my discord channel
can anyone help me make a discord bot ?
It still doesn't detect headers on new lines
Show your code
Nvm. It worked now
header_pattern = re.compile(r'^#+\s+.*$', re.MULTILINE)
if header_pattern.search(message.content):
await message.delete()```
I can still use re.compile
Yes
Thanks Cat
accept friend request
any idea why I receive this error when trying to install discord-component?
Collecting discord-component
Using cached discord_component-2.1.2.tar.gz (12 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [19 lines of output]
file = builtins.open(filename, mode, buffering)
FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
you don't need to download a 3rd party lib, discord.py supports components already
huh, it looks like an unofficial reupload of the original discord-component__s__ library that the author yanked
oh, okay
Dark magic related to discord onboarding (Server Guide) -> Resource
You can fit everything any text channel with @ everyone to view the channel. This make a good opportunity to hide auto role embed in there from bot. Even better, the author of the embed can be stay hidden on client-side which might be helpful in some case. Furthermore, you can add thumbnail, title and description to further descript to the user what they should do. (Example: Verification)
In addition, the resource button is being hidden if the user can no longer access the channel, which could make the whole process incredibly interactive (e.g. disappear after obtaining the role)
Extensionally, it doesn't have to restricted to channel that always visible to people just join. This can be accomplished by auto role a role that hide the channel on join/Using onboarding pre-join question to forcibly assign the role so people with bare @ everyone do not exist
Which therefore you can set freely on what resource to display to what user in the server (even tho It might mean the whole permission system have to be reworked)
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
ignore that ij forgot the website
hi
Does anyone know why the discord API doesn't want to interact with my user token?
401: Unauthorized
user token, as in not a discord bot's token?
user token, and the API detects it as a bot token and gives me an error
self bots (passing a user token) are not allowed and break discord tos
well, previously if he left me, out of nowhere now that comes out to me
and I have tools (selfbots) that do work well with my token, but not with my code, I don't know why
?
?
nvm, anyway. As selfbots are against tos, you won't be getting help for them here
hello i am new here. I wanna start to program a discord bot, any advice for me?
the general advice are to learn the python language first, learn all the fundamentals before creating discord bots, discord bots libraries uses advance concepts which will confuse beginners and become a huge brick wall on the simplest problems
can someone help me with this
Did you save the file?
Yeah

I saved it again and it says this now
You need to import commands from discord.ext instead, that's where it's from :P
Did you put the token into the run method like: bot.run("token")?
Doesn't seem like it, based on the traceback
Did you save the file?
yeah
Then the error should go away 
Nice 🐈
i need help
/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py:464: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/client.py", line 703, in _run_event
await coro(*args, **kwargs)
File "/home/runner/BattleEx/main.py", line 13, in on_ready
await bot.load_extensions("cogz")
TypeError: object NoneType can't be used in 'await' expression```
import aioredis,asyncio
from disnake.ext import commands
import os
from disnake.ext import commands
import os
class Redis(commands.Cog):
"""For Redis."""
def __init__(self, bot: commands.Bot):
self.bot = bot
self.pool = None
self._reconnect_task = self.bot.loop.create_task(self.connect())
#all funcs here
async def setup(bot: commands.Bot):
print("Here")
redis_cog = Redis(bot)
print("Setting up Redis cog...")
await redis_cog.connect()
await bot.add_cog(redis_cog)```
Only discord.py's extension and cog implementation are asynchronous. disnake's are synchronous
i used discord py too i gave same error
What is the version? The asynchronous implementation is added in 2.0+
;
latest version only
how do use async funcs in cogs
for disnake then
You cannot
then how do i use components in ctx.send in dpy @naive briar
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
i wanna use that components arg
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
Here
Setting up Redis cog...
Extension 'cogz.redis' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
/home/runner/BattleEx/main.py:23: RuntimeWarning: coroutine 'Redis.connect' was never awaited
print(e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded
print("Here")
redis_cog = Redis(bot)
print("Setting up Redis cog...")
gg=asyncio.run(redis_cog.connect())
what else can i do
you need to await whatever redis.connect is
Why is asyncio.run being used here...?
async def ticketcallback(interaction):
guild = interaction.guild
role = discord.utils.get(guild.roles, name="Ticket Support")
overwrite = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
select = Select(options=[
discord.SelectOption(label="Help Ticket", value="01", emoji="✅", description="This will open a help ticket"),
discord.SelectOption(label="Other Ticket", value="02", emoji="❌", description="This will open a in the other section")
])
async def my_callback(interaction):
if select.values[0] =="01":
category = discord.utils.get(guild.categories, name="Tickets")
channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrite)
await interaction.response.send_message(f"Created ticket - <#{channel.id}", ephemeral=True)
await channel.send("Hello, how can can I help?")
elif select.values[0] =="02":
category = discord.utils.get(guild.categories, name="Tickets2")
channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrite)
await interaction.response.send_message(f"Created ticket - <#{channel.id}", ephemeral=True)
await channel.send("Hello, how can can I help?")
select.callback = my_callback
view = View(timeout=None)
view.add_item(select)
await interaction.response.send_message("Choose an option below", view=view, ephemeral=True)
@bot.command()
async def ticket(ctx):
button = Button(label="📥 Create Ticket", style=discord.ButtonStyle.green)
button.callback = ticketcallback
view = View(timeout=None)
view.add_item(button)
await ctx.send("Open a ticket below", view=view)
Can someone help mewhy this isn't working
I get a button which says "📥 create ticket" but when I click it says "This interactions failed"
it also does not give errors
pretty sure its because thats not how you make a button
its something to do with the callback not being defined properly
since it requires arguments and you cant do what you’re doing if there are arguments there
you should define complex stuff like buttons in a physical class instead of a few lines
makes it easier to debug as well
what is this called or how can i do something like this?
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
you can also use typing.Literal or autocomplete, depending on what you want
I am having AttributeError: type object 'datetime.datetime' has no attribute 'datetime' error
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
can anyone help?
you probably did from datetime import datetime, in that case you want datetime.now() and not datetime.datetime.now()
why dont i get the button click event response
class BattleUI(discord.ui.View):
def __init__(self,bot):
super().__init__()
self.selected_button = None
self.bot=bot
async def start(self, ctx,pokemon):
for n,i in enumerate(pokemon.moves):
button = Button(style=discord.ButtonStyle.secondary, label=f"{i.move_name}", custom_id=f"{n}")
self.add_item(button)
def check_button(i: discord.Interaction, button):
return i.author == ctx.author and i.message == msg
message = await ctx.send("Please choose a move:", view=self)
interaction, button = await self.bot.wait_for('button_click')
print("Button clicked")
action=button.custom_id
print(interaction.data)
print(self.items)
await interaction.message.edit_response(view=self)```
Because button_click is not an event
Here's an example of how buttons actually work
so im trying to make a bot, kinda need opinion what you would have inside a guild setting , this is example of what i have stored
"alliance_settings":{
"alliance_description": "We are a powerful alliance!",
"alliance_roles":{"warlord":0,"diplomat":0,"resercher":0}
}
also im using json to just store data structure, actual data is made from that structure
so @glad cradle gib answer
ig json killed him
the structure how you store things is up to you
it just needs to be functional for you
there isn't a correct way
wel it is functional
but surely don't use json pls
also whats the harm in that?
how are you reading and opening the json file? file operations are blocking
with open ("data.json","mode") as fh:
data=fh.load
fh.dump(data)
oh ok
ill keep that in mind in future
rn, this is just a personal discord bot
also answer this
fh.load ?
what more can i add?
youre supposed to use json.load() right
i forgot the brackets
and json.dump
yea
No
iforgot lol
been long time since i made a bot
anyways thats not an excuse for me
i shall fix my mistakes immediately
And also for your original question it completely depends on what you're trying to do
Just store the data which you think your bot needs to use
And if you're using mysql or sqlite etc use an async library of it
im trying to make an rts game with alliance system
so need nommethings that i can put in there
Well that completely depends on you, I haven't seen your codebase so see what all data you exactly need to store
its just additional info
imma get full structure
"server_id":{
"leader":0,
"alliance_name":"no name",
"alliance_battles":0,
"alliance_battles_won":0,
"alliance_battles_lost":0,
"alliance_power":0,
"alliance_members":[],
"alliance_allies":[],
"alliance_settings":{
"alliance_description": "We are a powerful alliance!",
"alliance_roles":{"warlord":0,"diplomat":0,"resercher":0},
"alliance_ranks":{"rank4":[],"rank3":[],"rank2":[],"rank1":[]}
}
}
That looks cool
thanks, but it's really not
as a solo dev ive been trying my best for past 2 years along with acedimic studies(im not even in collage right now, im undergradguate) The actual time i spent on this bot may be around 15-30 days
I for a moment thought he was real sarth 😭
Haven't seen them for a while
Good team 
also i may have lied about that
heres proof
also @weak tendon wdym by real sarth?
is there something im missing?
anyone?
are you doing this at the start of your Bot?
mh then it should be fine even tho not reccomandable
writing on the file is another thing tho, always blocking
im doing it inside every function
then that's bad
cause when im calling thee fuction, data needs to be updated contounisouly
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
there was no other way
welp i got my exams
and im not currently comdortable
thats why ive been avoiding it
we have a friend with the same username
oh
i see
ig something happened to him?
well there are 9 of us in this server
mh, ic, switching to a database shouldn't be too hard and shouldn't require much code changes, i would suggest to not focus on the data storage on json files, instead focus on the functionalities, so you will not waste time on a thing that you'll surely switch later
yeah ig he's crying really hard on college exams or slacking off
probably the latter
idk, iirc yes
@meager rock this one
kk
migrating is easy dont worry. all you need is just to learn a little SQL (probably takes a week for the basic operations) and then learn how to use a db (learn under 30 minutes)
i wrote two gists on this sort of stuff but idk if i can send the link
i learnt in 1 day
might be classed as self promotion
just not used to using it
How use from src.settings import config
learn how to use asqlite after
ok
i dont really follow that
src.setting
its a wrapper around sqlite3 so go in this order:
sql -> sqlite3 -> asqlite
ohk
put it at the top of your file?

shouldnt that have been the first thing you tried?
btw i feel like im very far behind in comparision to you guys, where did u learn all this from?
im assuming experience

literally trial and error
and just commitment
once you get in the water, swimming becomes a lot easier
I'm committed lol
Tho don't have much time as I'm also managing school
This is last year, I'm going to collage soon
no by commitment i mean just having the balls to dive head first into it and see what happens
oh good to hear. 👍🏽
I have 1 question
Why, for example, when I put ready.py in an events folder, it doesn't find it?
because its in a folder
basically it’s looking at everything NOT in folders when you write something normally
like open(“filename_here”) will check if its in that folder
to look for stuff in other folders you need to do folder.file
so if filename_here was in another folder, it would be parent_folder.filename_here
hope that makes sense for you ❤️
Python 3 comes with a new module named Pathlib. Since Python 3.6, pathlib.Path objects work nearly everywhere that os.path can be used, meaning you can integrate your new code directly into legacy code without having to rewrite anything. Pathlib makes working with paths way simpler than os.path does.
Feature spotlight:
- Normalizes file paths for all platforms automatically
- Has glob-like utilites (eg.
Path.glob,Path.rglob) for searching files - Can read and write files, and close them automatically
- Convenient syntax, utilising the
/operator (e.g.Path('~') / 'Documents') - Can easily pick out components of a path (eg. name, parent, stem, suffix, anchor)
- Supports method chaining
- Move and delete files
- And much more
More Info:
from src.events import ready ?
yeah
Depends on your files and folders
Ah well, I was doing it well but it still shows an error that it cannot find
change the file directory to the file so that the slashes become dots
so if its ./src/events/ready.py, that becomes from src.events import ready
Who put this logo down inside my footer but when I do I just get the application. Did not respond in no error inside of my log
@app_commands.command(name='warn',
description="Warns a specified user.")
@app_commands.checks.has_permissions(manage_roles =True)
async def warn(self, interaction: discord.Interaction, user: discord.Member, *, reason: str = None):
em = discord.Embed(color=0x7289da)
em.add_field(name=f'Warn Successful', value=f'You have been warned in **{interaction.guild}** by **{interaction.user}** for `{reason}`')
em.set_footer(icon_url="logo.png", text="Echo Discord Bot")
await interaction.response.send_message(embed=em)```
can you rephrase? im not understanding what you’re saying
So when I put in the icon URL into the footer the command no longer works. But when I take it out the command works when it doesn't work. All it says is did not respond to command
so the command works with no image in the footer but doesnt work when you add the image to the footer
ah i know what it is
icon_url takes a web link and “image.png” is not a website link
?tag file
This is not a Modmail thread.
oops, forgot this isnt dpy
So is there a way to do it without a web link?
yes but you have to do this
(taken from dpy)
Want to upload a local file to discord?
# First create a discord.File object
myfile = discord.File('myfolder/my_local_file.png')
# or
myfile = discord.File(my_buffer_that_i_created_previously)
# and then send it via .send()
await ctx.send(file=myfile)
docs:
- discord.File: https://discordpy.readthedocs.io/en/latest/api.html#discord.File
- abc.Messageable.send: https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send
thx
Okay, so I have a simple issue, I have a calculator command, which uses eval, how can I make my bot not crash when someone does 9^9^9^9 or maybe something bigger? I don't want a limit on it where they can only have this amount of exponents, but I want it to return a custom error if the eval failed, but I don't want my bot to go offline either, how can I prevent this?
@discord.ui.button(label='=', style=discord.ButtonStyle.green, custom_id="=", row=4)
async def equal(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message("This button isn't for you. Just run the command yourself goober.", ephemeral=True)
return
if interaction.user.id == self.ctx.author.id and not self.disabled:
expression = self.value.replace('x', '*').replace('÷', '/').replace('^', '**')
try:
try:
result = str(eval(expression))
self.value = f"{self.value} = {result}"
self.clear_on_next_input = True
except Exception:
self.value = "The provided equation is invalid!"
self.clear_on_next_input = True
except ZeroDivisionError:
self.value = 'Infinity'
self.clear_on_next_input = True
except Exception as e:
self.value = "The provided equation is invalid!"
self.clear_on_next_input = True
embed = await self.update_embed(interaction)
await interaction.response.edit_message(embed=embed, view=self)```
prob should ask in #python-discussion cause this channel is barely talked into unless someone just checks in
and its an overall problem
is there a Discord library available that is an actual API wrapper (closer to 1-to-1) and not a phat framework in which to nestle your little snippets of python and watch it play with them?
https://docs.hikari-py.dev/en/latest/
ive never tried hikari but you might be interested in it, hikari seems to expose more "lower-level" interfaces compared to discord.py
see also their REST client reference:
https://docs.hikari-py.dev/en/latest/reference/hikari/impl/rest/
That's actually what I'm currently migrating away from, although I only use it in a more framework fashion. I'd like to be able to use the gateway api and the only way Hikari lets you do that is through the gatewaybot class.
hmm, what are you looking for that the class doesn't provide?
the ability to finely control the main run loop
So that I can have external functions trigger depending on the actual status of the bot instead of starting a second thread and giving it a stop flag with a try/finally, as well as have external functions cause the bot to do something without needing to break out to the rest api in the middle of a bot that's literally built in the gatewaybot class
can you not just set a cap on the result size? and whats the issue with a quadruple exponent tower? does it take too long or end up as too big of a number?
you might want a math tokeniser that can manually execute operations from a string as that way you can control limits from there: as 9^9^9 is already in the billions or even futher
try and find something online that will suit your needs
im kind of confused why a second thread is needed given that hikari uses an asyncio event loop, though curiously it doesnt look like they have a simple async alternative to GatewayBot.run() which is kind of weird - i would have assumed GatewayBot.start() would be that, but it just returns after the shards are connected, so i have to guess from the source code that user needs to call join() and close()...
well regardless, i don't have any other libraries in mind, but i would try to figure out if you can manage the asyncio event loop without using GatewayBot.run(), that way you can start your own asyncio task and do your own work while the event loop is running, something like: ```py
@contextlib.asynccontextmanager
async def start_gateway_bot(bot):
# Handles startup/teardown of a GatewayBot
await bot.start()
try:
yield
finally:
await bot.close()
# NOTE: this might not be sufficient, hence why I'm confused that
# hikari doesn't have this - maybe worth a GitHub issue?
async def my_status_updater(bot):
# Do something every minute indefinitely, or whatever
while True:
await asyncio.sleep(60)
await send_status_update(...)
async def main():
async with start_gateway_bot(bot), asyncio.TaskGroup() as tg:
tg.create_task(bot.join())
tg.create_task(my_status_updater(bot))
# If an error occurs, TaskGroup will cancel join()/my_status_updater()
# and allow the bot to be cleanly closed
# (requires Python 3.11+)
asyncio.run(main())``` alternatively if you're interested in the technical details and you have the time, you can try writing your own gateway wrapper (see api docs and my attempt)
I fixed it to just use an API that will handle it all. The reason why 9^9^9^9 would crash the bot is because its just to big of a number, and will completely end the bot. The bot won't send an error or anything, on your console/terminal it says its still running even tho its not. It was just an eval issue, so I took out eval and used an api. This api does everything for me without me having to worry about its failing.
@discord.ui.button(label='=', style=discord.ButtonStyle.green, custom_id="=", row=4)
async def equal(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message("This button isn't for you. Just run the command yourself goober.",
ephemeral=True)
return
if interaction.user.id == self.ctx.author.id and not self.disabled:
expression = self.value.replace('x', '*').replace('÷', '/').replace('+', '%2B')
try:
async with aiohttp.ClientSession() as session:
async with session.get(f'https://api.mathjs.org/v4/?expr={expression}') as response:
if response.status != 200:
self.value = "The provided equation is invalid!"
self.clear_on_next_input = True
else:
result = await response.text()
self.value = f"{self.value} = {result}"
self.clear_on_next_input = True
except Exception as e:
self.value = "The provided equation is invalid!"
self.clear_on_next_input = True
embed = await self.update_embed(interaction)
await interaction.response.edit_message(embed=embed, view=self)```
Then the command will look like this at the end, which I think looks pretty good!
Its like a literal calculator inside of discord, which is funny and cool at the same time, took me like 1-2 hours to do because of the eval stuff, which an api took over because its just easier that way.
holy shit thats fire whattt 😭
idk why i didnt think of doing something like this sooner
How could I start breaking up my bot code to get better organized?
amazing, great idea 👍🏽
how disorganised is it?
i say grab some paper and outline what your bot is and does. draw a spider diagram where all the features extend into other features
First there are the libraries, then the bot, then MySQL and the tables, the on_ready the events and commands and finally the token
Main.py / config.json
then you can generalise these into cogs, multiple cogs into multiple files and multiple files into folders
are these libraries pip installations?
or libraries made by you
which congrats cuz thats a lot of work to make a whole library
Yeah
yeah dw about that
have your files structured like this:
- imports
- classes — this counts as views, buttons and anything else
- main cog code
- abstracted functions
- commands
- setup func
something i learned to save space is to list them like this:
import thing1, thing2, thing3, thing4
instead of like this:
import thing1
import thing2
import thing3
import thing4
Because?
looks neater imo and if you have a bunch of imports it doesnt crowd the top of the file
Ohh thx
i suggest the paper strategy because it gives you a visual representation of what your bot does or is supposed to do
Yeah
Thank you lol
I did it because, you can always have a command that does calculations, but you would have to restrict like words, and so many other things, with this, you can't enter anything you want, you have to do what the buttons want!
And how do I organize my MySQL db?
fantastic. congrats on the calculator design, i love it! 🔥
depends. what does it hold?
Thank you, currently I am taking out the root button to add an ANS button, basically so you can use the last ans in your next equation.
ah alright. its a bit difficult deciding what you want to include considering the 25 button limit
what do AC and DC do?
wdym by disables it?
ill just send video
like turns it off?
oh alright thanks
What do you mean?
Just makes it not useable no more, but there is almost a timeout of 120 second (2 minutes), so just incase they don't disable it, it will do it on its own!
oh it disables all the buttons
Yeah
yeah i would say to replace DC with an ANS key since it’s gonna disable itself
and then lower the timeout from 120s to like 45s
I mean I could
you dont really need a 2 minute time period 😭
Maybe they wanna come back? 
i’d suggest it since the square root button is also vey help
idk I put high time on it just incase
Okay, Ill add it real quick lol
if you end up leaving for longer than a minute smth up w you
you can also make it green to break up the other colours
i like the pi button, nice touch
So something like this?
yep, perfect
make the sq root blurple tho
cuz its not a number its an operation
yeah
and the obelus is pretty hard to see
swap it with a slash (“/“)
past that, no other improvements
what character did you use for the backspace?
⌫
🔥
I am gonna keep it, because I personally like it, but thanks for the suggestion!
good you’re choosing your own decisions when they’re more favourable to you. great trait to have. enjoy your evening, its 1am for me so i’ll sleep now 👍🏽
Have a good night!
Final product tho! Looks clean, thanks for all of the suggestions!
And everything works just how I expect!
amazing 👏🏽 be proud of yourself because this took a lot of time and effort, especially with the UI and UX.
i might need to take a page out of your book when it comes to UI now that I think about it
Thank you!
Looks very nice but now look at it on mobile
Oh alr then
just the ANS button
We had a command in bobux bot that looked good at pc version (5 rows of buttons) but on mobile it was just damn vertical buttons list
lol
it looks good enough on mobile imo
Basically because they are all the same length in text thats mainly why
veri cool
guys anyone has created twitter bot recently?
Ty
cool stuff
no i dont think so. why do you ask?
anyone know to fix this?
That's not how you make slash commands in discord.py 🫠
See the official example
how to fix the error
See the official example to make them correctly 🤷
having issues in creating bot
drop the code, lets see
i just put it in python help
check the example given by catlover
This is a channel about discord bots, so I don't think there's any Twitter bot dev here 
i specialise in discord bots so i cant help with twitter bot dev unfortunately. plug it in python disc, maybe they can help 
ok
how could i fix that?
reduce the embed description size
Hello asher when bobux stats ☺️
Yeah, that’s how you would do it in Nextcord
nextcord for real 
I have a embed whose description always expands automatically when someone is warned, but since embed have a max length, i dont know how i can do this in the future now
Well I prefer it due to it just being a lot easier to make slash commands
real
Use Fields, here’s an example.
embed.add_field(“ID”, f”{row[2]}”)
Fields don’t count towards the description but they still add to the embed
yea and how can i automatically add a new field once someone is warned?
there has to be a max embed fields
the max character limit in the entire embed is 6000 so you will eventually need a new message
https://discord.com/developers/docs/resources/channel#embed-object-embed-limits
have you considered showing only the most recent warnings in your embed?
or you can make a paginator
im assuming its a persistent message given that the embed is "automatically updated", in which case giving paginator controls to everyone that can access it might get a bit awkward
You would have to make buttons/reactions that would cycle through the warnings
but otherwise for temp/ephemeral embeds that'd be a good idea
hey guys can you guys help me for my assignment so i create a discord chatbot for these
- Identify suitable plants and provide advices on good practices on taking care of the plants;
- Monitor real-time plant growth conditions like temperature, amount of light intensity, soil moisture, pH level, with consideration of geographical and weather information;
but i use my command it didnt show the result I want
import discord
from discord.ext import commands
import requests
Define intents
intents = discord.Intents.all()
Initialize Discord bot with intents
bot = commands.Bot(command_prefix='!', intents=intents)
Define API endpoints
PLANT_API_URL = "https://trefle.io/api/v1/plants"
WEATHER_API_URL = "https://api.openweathermap.org/data/2.5/"
Function to fetch plant information
def get_plant_info(plant_name):
# Make a request to the plant API
response = requests.get(f"{PLANT_API_URL}/plants/{plant_name}")
if response.status_code == 200:
return response.json()
else:
return None
Function to fetch environmental data
def get_environment_data(location):
# Make a request to the weather API based on location
response = requests.get(f"{WEATHER_API_URL}/weather/{location}")
if response.status_code == 200:
return response.json()
else:
return None
@bot.command()
async def plant_care(ctx, plant_name):
plant_info = get_plant_info(plant_name)
if plant_info:
care_advice = plant_info.get('care_advice', "No care advice available for this plant.")
await ctx.send(f"Care advice for {plant_name}: {care_advice}")
else:
await ctx.send(f"Sorry, I couldn't find information for the plant '{plant_name}'.")
@bot.command()
async def monitor(ctx, location):
environment_data = get_environment_data(location)
if environment_data:
# Parse environmental data and send to Discord
await ctx.send(f"Environmental data for {location}: {environment_data}")
else:
await ctx.send(f"Sorry, I couldn't retrieve environmental data for the location '{location}'.")
Run the bot
bot.run("discord token")
dayum
what result did it show?
this
fucking doing for 2 weeks and even ask help from the damn ai still no fruit
hmm i did no let me try out other website
I believe the access tokens are free on that site, so you can just make an account there and get one if you want
yea my dumbass use wrong link it works
nice
select_callback
if interaction.message.components[0].custom_id == "ticket_select":
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ActionRow' object has no attribute 'custom_id'
help me
The first component is ActionRow and it doesnt have .custom_id attribute
need to acces the children, message.components[0].children[0].custom_id
can you fetch user about me's using bot authentication ?
How do I fix

This will only work when its ActionRow component
When its Button or else it wont
pretty rare to see message.components being used though... are you sure you couldnt set select.custom_id = "ticket_select" and add it to a persistent view instead?
oh wow I dind't read that properly. Definitely that ^^
.
how do i give / commands an option?
like
music = f"video url or name"
and it gives me what they put in?
A hands-on guide to Discord.py
ok but how do i
get the returned varible from a function?
you get it as parameter to function
whats the max amount of parameters slash commands can have as Optional inputs for discords UI?
Anyone truly have a working Music bot using Lavalink?
I have tried for many days, and I feel like I have gotten no where, so if someone has a WORKING one, please let me know, its really annoying. I just can't get it to work in anyway. I got a working Lavalink server, just not a working bot I guess.
how can i send a dm message to a user wich is given by user id using slash commands?
https://github.com/richardschwabe/discord-bot-2022-course/blob/main/cogs/music.py
this was the first tutorial i watched on yt a while back and used it. haven't tried it recently.
Does it support multiple servers?
Couldn't get it working
so idk, I truly can't find one that works.
is it for streaming youtube music
Just for a music bot yeah
well most sites like youtube and spotify dont let you do that so thats probably why
You are allowed to do it, but it just breaks their ToS
that means you aren't allowed to
and anyway, we don't really help with music bots here because of rule 5
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
I thought violate tos was only for discord?
no we can't help you violate any other ToS either
I didn't know it covered like overall, so thats my bad
alright, thats my bad, thought it only covered discord tos
anyone have any clues
Does anyone know a good spot where people can review my bot and just do testing on it?
friends
Wish I had some 
me too!
Yeah
I need people to test and review it 😭
So thats why I am asking here to see if anyone knows a good spot for others to just test the bot.
Well first off, why do you have all of these options enabled?
they are required for the bot to work
How so?
not for voice usage. and message usage
mhm
and for voice all you would need is a voice permission which is inside of permissions, not scopes.
you need the scope
No you do not 😭
why you using applications.commands.permissions.update?
/cmds.
thats not needed for slash commands either.
mhm
Bro, I have a verified discord bot with slash commands... and it does not use that scope.
It only uses bot.
ok then what is it?
this is all you need if your bot is just a basic bot.
The rest is usually for like websites n other stuff. But since you are most likely doing everything inside of discord, you won't need that.
anyone know this answer?
I'm not sure but it should be as many as you like
You can make all your params optional if u want to
like if i wanna pass through an optional amount of parameters like 20 roles, would it work?
Should work but u should try and see
Since they are params so it shouldn't be a problem unless you are talking about buttons
Which is 25 for each msg
I thought parameters were 20?
Parameters are 100% 20 or 25.
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 63.options: Must be 25 or fewer in length.```
you will get this error if you go over 25.
thank you! I actually just found out u need to send the parameters as snake_case or i got errors. weird.
are you using dpy..?
what is snake_case...?
oh im slow 
Simple google search helped me 😭
lol
Yeah you can't use spaces unless its like an Enum or Auto Complete I am pretty sure
naw i tried js formatting
Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'limit_list' defined in function 'ModeratorTestSlashCommands.limit_list'
In parameter 'roleTwo'
name: Command name is invalid
yeah
once i swapped em to snake_case they worked lmao
gotta do role_two or role-two
or just roletwo
But what you can do is, to make it look nicer..
from discord import app_commands
@app_commands.describe(paramater='description')
so for an example you could just put 2 instead of role_two
and the describe will let you put a description for that paramater
ohhhh
which shows up above in slash commands.
if you want it to look nicer thats what I suggest, but thats up to you. either way the main goal is to have the bot work at the end lmao
How do I create buttons with Python?
Actually, don't use that example
no that's actually perfect! thank you for the help.
So I made my own discord.py template, which shows buttons, which is the latest way of doing it.
https://github.com/RejectModderss/Discord.py-Template/blob/main/views/example.py#L97
Ok
yeah, the old one I just showed you is a little outdated in a way
No problem! Hope it works out!
wait, how can you put a 2 as a parameter o.O
like _1? or am I missing something
wait can you not do numbers?
oh, I didn't know you needed 2 characters, that is my bad!! You can just do one, two, three instead of roleone, roletwo, rolethree?
I didn't know you needed 2 characters for a parameter to work, I am sorry.
Did you ever get those buttons working? Or are you still needing help, because I can always help you!
no. no it's okay. a semi-clean way you gave me the idea for was just to do
_1 = "Role 1"
Not always but some specific cmd output print 2 times.this does not happen with all cmd just with few commands. idk whats the issue.
if interaction.select.custom_id == "ticket_select": AttributeError: 'Interaction' objecy has no attribute 'select'
Shocking
I know why
await bot.process_commands(message)
if you have this in an on_message event, then you will have it do it twice.
oh!! but it does not happens with all command only with few
You are using cogs right?
Each cog can have its own on_message event, meaning not all of your cogs have an on message event, but any cog with an on message event and have await bot.process_commands(message) it will send twice
Thats just from expirence tho!
@keen lynx did you fix it, or is it still happening?
no i haven’t fixed it yet, thnx for the ping so, what's exactly is the fix bot has 200+ cmd with 20+cogs it happens with only 3/4 commands. await bot.process_commands(message this only exist in main.py no cogs has it
take it out of main.py
you have no reason to have it in main.py, you honestly don't need that
i do need it. it's very important i guess lemme fetch the code
@client.event
async def on_message(message, **kwargs):
#message.content = message.content.lower()
msg = message.content.lower()
if message.author == client.user:
return
if message.content.startswith("Sudo "):
message.content = message.content.replace("Sudo ", "sudo ")
await client.process_commands(message)
!d discord.ext.commands.Bot - you can turn case_insensitive on to make the bot ignore cases for the prefix/command, so you don't have to do it manually
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
You don't need it.
ok i will try. thank you.
np
I have never needed
bot.process_commands(message)
it worked. yeah no need of it
prefixes = ["Sudo ", "sudo "] # Add all your prefixes here
super().init(commands.when_mentioned_or(*prefixes)
Mhm
You will never need that in your bot
Unless its an all 1 one file, then you will never need it
Can we log deleted media files ( videos , pdf , exe , XML , )
Ik we can log images
How do I fix?
Don't try to access attributes that doesn't exist
Where did you get the interaction.select from anyway?
What do you mean
Where did you get the idea to try and access a select attribute of interaction? That doesn't exist
Maybe you're mixing different libraries?
I followed a tutorial on YouTube
1-is there free good api, 2-can build discord bot with python?
- api for what?
- yes, there is nextcord, discord.py, pycord and many more
not bot need api?
are you taking about free hosting for the bot?
can bot work in discord server-channel for 24 without my pc
if you don't want to use your pc to run the bot, there are a few, decent-ish free hosting - but if you want guaranteed 24/7 (not including server down time for upgrades or whatever) you should look into a paid hosting service
like what ?if you help me with some name, cuz i spend time try some and work for 2 h and stop
and may i ask about something, why bots not run on channel it self inside the discord servers?
its logic that channels work on pc servers like bots
discord doesn't host bots, it's up to the developer to keep the bot online
just google discord bot hosting, whether you want free or paid you'll be able to find it.
you give me your time, and care ,and helped me🙏
Is there a discord.py updated that does error handleing different I can't see errors in my console now
Are you running the bot with the .run method? If not, you'd need to setup logging
!d discord.utils.setup_logging - or use this convenient function
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.
New in version 2.0.
This looks fun
read the error
does anybody know why the message isnt "ephemeral"
from discord.ext import commands
import random
bot = commands.Bot(command_prefix='.', intents=discord.Intents.default())
laby = {1 * 100}
@bot.event
async def on_ready():
print('Ready')
@bot.comamand()
async def ping(ctx):
await ctx.send(random.randint(laby))
bot.run('')```
@bot.event
async def on_member_join(member):
channel=bot.get_channel(924384859923837018)
em=discod.Embed(title="test", descriptipn=f"{member.mention}")
await channel.send(embed=em)```I have this welcome message doesn't seem to work and I've get no error inside of my log. Any thoughts? I'm out of ideas
async def is_it_up(interaction, site: str): if not site.startswith("https://") and site.startswith("http://"): if site.startswith("www."): site = f"https://{site}" else: site = f"https://www.{site}" try: r = httpx.get(site, timeout=5) #if the status code is 200 then the URL is up if r.status_code == 200: await interaction.response.send_message(f"{site} is up :)") #if the status code is not 200 then the URL is not up except Exception: await interaction.response.send_message(f"{site} is down :(")
So i'm trying to make a command to check if a website is up, and I want it to allow both http:// and https:// sites, it worked fine when i did it on command line but now it's not working
it only works for https://
are you using ctx.defer?
I know why, you are putting discod.Embed, its discord.Embed.
If you change that, then it should be fixed!
🤦🤦🤦 thanks
async def is_it_up(interaction, site: str):
if not site.startswith("https://") and not site.startswith("http://"):
if site.startswith("www."):
site = f"https://{site}"
else:
site = f"https://www.{site}"
try:
r = httpx.get(site, timeout=5)
# if the status code is 200 then the URL is up
if r.status_code == 200:
await interaction.response.send_message(f"{site} is up :)")
else:
await interaction.response.send_message(f"{site} returned status code {r.status_code}, it might be down :(")
except Exception:
await interaction.response.send_message(f"{site} is down :(")
No problem!
yeah I figured it out, this is close to the solution tho
Not how you should do ping, what you should do is
latency = round(bot.latency * 1000)
Also I recommend switching to aiosqlite, instead of just regular sqlite!
i did tysm
Also, I recommend using aiohttp! Its a better library than httpx.
eh, i'll use httpx for now
but thanks
^ it's not just better, it's async, which means it doesn't block your code. Your bot will freeze for the amount of time httpx.get takes to yield, which could cause problems. Further, you should be careful with how you handle user-inputted URLs. There's always that not-so-nice user that might try to do something malicious and screw you over, @ocean spindle.
Yeah, making it better xd
Also, they should probably open the links within a save enviroment, just incase.
Or make the command developer/owner only.
httpx itself also includes an async client
I did not know that.
Ive always used aiohttp so i guess I never looked into that. But nice to know, I just think aiohttp is really good.
I didn't know either until about 10 seconds ago haha
lmao, thats fair
how would i go about doing that?
should I run my bot on a VM?
What you could use is
uptimerobot which will do the stuff for you, it will check if the website is up or down
Which is ran in a save environment.
or isitup.org something like that would work I think
I think isitup.org was removed actually, so I guess use uptimerobot
it only allows 50 requests
per?
Actually, here, you could possibly use
They are a good website
ngl I'll prolly just remove the command for now
alr lol
like refresh in what way?
you are on pc?
ye windows
didn't work
are you syncing?
You need to sync the command, then refresh discord
ill send a video of this working 😭
in the on_ready function?
are you using cogs?
also, never put anything inside of on ready :)
why not?
no
do you know cogs?
nah
Here, I am going to give you my template, which shows cogs, and you can see I never use on_ready to do any of that, also this has a custom sync command. Which you can run each time you need to sync!
This is a discord.py template for cogs and sub commands! - RejectModderss/Discord.py-Template
This teaches cogs, sub commands, hybrid commands, prefix commands, buttons, drop down menus, and more.
Looks nice! though not sure if I like the naming scheme for the modules. This is how I did mine: https://github.com/Robin5605/discord-bot-template
Whats wrong with them?
Also thank you, I do cogs differently from how others do it, I never understood how others did it with the setup at the end of the py files, so I just did it this way, but someone taught me to do it this way. Loading them with the setup at the bottom of each py file is better imo because you can unload each extension instead of all of the extensions but its fine lol.
modules should be snake_cased
your package names are a pep 8 compliance violation of utmost egregious-ness
https://peps.python.org/pep-0008/#package-and-module-names
also unnecessary usage/nesting of namespace packages, but thats not too important
^ i too have been structuring my (newer) bots in a single, top-level package
https://github.com/thegamecracks/thestarboard/tree/main/src/thestarboard
Well, I didn't really think it mattered at the end of the day
code cleanliness is probably just as important as functionality
nice! i like this, i might steal some ideas
Sorry lol
I didn't really know, I thought it didn't effect it
for python applications in general, whatever file structure works and looks nice will be fine
I mean, that code runs perfect, but I am a little confused on what parts you guys want me to change
Are you guys talking abt the file names?
im not saying you should change anything cause it works fine, its just a bit unconventional
"conventional" package/module naming would be snake_case
Oh, okay, I was just a little confused on if you guys were trying to say it would effect the functionality of the bot or what lol.
But that won't effect the project correct if its not snake_case?
nope, just how your imports look
oh yeah i didnt mean to be claiming they were serious issues, just file aesthetics
Yeah thats what had me confused, I was oh shit is this gonna cause issues in the future?
But glad you cleared it up lol, kinda had me worried on something I never knew or thought about.
i'm curious, though - how are you doing your migrations? is it all in the docker-entrypoint.sh shell script? do you simply run the numbered .sql files in migrations/ one by one?
still cant get it to work py @bot.event async def on_member_join(member): role = discord.utils.get(member.guild.roles, id=924252667809779733) await member.add_roles(role, atomic=True) channel = bot.get_channel(924384859923837018) em = discord.Embed(title="Welcome", description=f"Hello {member.mention}, Welcome to", color=0x00ff00) em.set_footer(text=f"test") await channel.send(embed=em)
just add this
@bot.event
async def on_member_join(member):
try:
role = discord.utils.get(member.guild.roles, id=924252667809779733)
await member.add_roles(role, atomic=True)
channel = bot.get_channel(924384859923837018)
em = discord.Embed(title="Welcome", description=f"Hello {member.mention}, Welcome to", color=0x00ff00)
em.set_footer(text=f"test")
await channel.send(embed=em)
except Exception as e:
print(f"{e}")
also what is atomic?
what do you mean
You know that's a very good question

Also, that doesn't return back to anything
Yes
Here, let me join the testing server and Ill help you?
Ill use my own bot for testing tho?
Yes
okay, just send the invite in my dms
Issue fixed, was just missing intents.
yes, i was experimenting with having the database container do its own migrations instead of running them from the app - it was kind of awkward and still left me the question of how i would deal with different branches... i remember reading something about simplifying migrations to dev -> staging -> prod without tracking a bunch of ordered scripts, but i cant for the life of me find that article again
aw 😦 that's one of my biggest pain points
guys how i can mention all members with bot on my server
you should just use everyone mention instead of doing individual mention
I mean dm
so mass DM? you're gonna get ratelimited doing that
thats against tos.
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
?
read this.
ok
Its against ToS to do mass dm.
how are you even supposed to learn
how to write discorad bots
i get confused in the documentation thing
YouTube, Documentation, Templates, People
oh yeah thats true
but like does discord expect you to just look through the documentation
and learn from there generally
yea
i use aiomysql
how can i tell the bot so it automatically reacts on its own messsage after he sent it?
i tried looking it up but the way i found it everywhere is not working
message = await xxxxx.send("hello")
await message.add_reaction("👋")
thats what i kinda tried but since im working with @bot.tree.commands i used interaction
after you send your .response,
msg = await interaction.original_response()
since .response.x methods always return None
i think i understand thank you
yes, discord.py is an advanced library and it's generally expected you know python well and how to read docs efficiently
doesn't mean you can't learn it if you're a beginner, though. it will just be harder
idk what this means but here you go
start small, do your research, watch tutorials, ask for help, get used to writing whatever code you're doing and you'll get there eventually
isnt there already asqlite for this sort of thing?
https://github.com/Rapptz/asqlite
they both allow you to use sqlite asynchronously ¯_(ツ)_/¯
Hya, a little question here. I have uploaded the ffmpeg.exe file to my bot repo, what should I do in the settings.py file to define the dir of the ffmpeg ans use it from there in the code? Idk if I explain myself xd
I mean, how do I run the exe with the config I have already defined in a list for the ffmpeg using the EXE in the repo
Thats why
For regular sqlite no
whats the difference between asqlite and aiosqlite then?
this doesnt sound like discord bots 
It is :b
it's for a personal music bot
to run it when the bot is starting up?
Nope, I want to host the bot
buut i need to use the ffmpeg exe that i uploaded to the repo insted of the PC's one bc it is being hosted
so the "server" does not have ffmpeg installed
Idk if I'm explain myself. Am I? xd
noted. after fighting with boto3, and trying later with aioboto3 and aiobotocore for half the day yesterday trying to get asynchronous AWS integration working... I finally got it working after abandoning all hope w/ that and using asyncio.create_subprocess_exec() and a cli tool.
Don't use aioboto3 lol, it lies... it LIES!!! it killed my bot whenever it ran lol. Cut off its blood supply and left it lifeless. :(
||did you forget to reply to a message lmao||
explain in simpler terms
im not understanding
nah this is just documenting for future peeps who do similar stuff. Ik when I'm doing something and having issues I'll often use Discord's search to see if anyone else has had a similar issue. This came up blank so I was on my own. Hopefully the next person won't be. :)
Bro, I said regular sqlite 😭
you're trying to upload files to S3, right?
i believe you can just do that over HTTP
idk what you're talking about anymore 
