#discord-bots
1 messages · Page 972 of 1
as I've already said it saves my namespace, so instead of doingpy import discord embed=discord.Embed(colour=discord.Colour.teal()) I can just dopy from discord import Embed, Colour embed=Embed(colour=Colour.teal()
i see
yeah it's a bit of a niche use case, if I wanted a random colour then I'd just do Colour.random() but I don't want a random one I want to iterate through them all so that I can send a embed with each colour so see what they look like (for example)
Don't they have all of the colours in the docs?
that's terrible practice, it clutters up your namespace with a load of stuff that you won't use
You can just put all of the different discord.Colour objects inside the list and iterate through that
Cause there probably isn't a way to iterate through discord.Colour but i could be wrong though
they do list them all but they don't give image examples of what they look like which is what I'm looking for. Guess I'll take that advice and make a custom list to iterate through
Unfortunately i think you'll have to try every colour out
lazy best way
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import
*statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from which library does a particular function came from. The risk of overriding the variables/functions etc always persist with the import*practice.
- Code Readability : It is always remains a mystery what is imported and cannot be found easily from which module a certain thing was imported that result in low code readability.
- Polluting the namespace : import
*imports all the functions and classes in your own namespace that may clash with the function and classes you define or function and classes of other libraries that you may import.- Concrete possibility of hiding bugs
- Tools like pyflakes can’t be used to statically detect errors in the source code.
i said 'lazy', lazy people rather take the easiest way
leaving the problems
you could.. ```py
colors = [getattr(discord.Colour, c) for c in [x for x in dir(discord.Colour) if not x.startswith(("_")) and x not in ["r", "g", "b", "value", "to_rgb", "from_rgb", "from_hsv"]]]
for color in colors:
...
when i run a command, my bot send the command twice. can someone help?
i look over the code and nothing wrong
You could be running your bot twice
wdym
you have two instances of your bot running
either find out where that other instance is or regenerate your bot token
multiple instances of your bot are running
so the problem is on_message event?
no
i googled it and it says process_commands
your bot is running twice
so if i stop it it still running?
i usually just regenerate my bots token
ouh ok imma try
everything is back to normal when i regenerate my token. thanks for helping
https://www.toptal.com/developers/hastebin/tafijevabe.rb
How do I disable all buttons and dropdown if a button with custom_id == "cancel" have been clicked ? see line 82
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
self.stop() ig
where to add ?
show your code
^^^^^^
in the url
oh, my bad
try put this at the end of async def callback
wouldn't that only work for dropdown ?
One message removed from a suspended account.
One message removed from a suspended account.
AttributeError: 'ItemSelection' object has no attribute 'stop'
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Hi, do you know how to detect the connection of a member on my server to react to his connection? (not on_member_join which reacts to the 1st connection / registration on the server)
You mean @client.command() @plain perch
You made it an event
Wait, what do you want to do?
One message removed from a suspended account.
So if a certain user sends any message in the presence of the bot, it gets deleted?
that button_callback in your cog is an odd way to run your code, why not write each implementation in the view methods instead?
well regardless, you can either call the stop() method the View class has (not the select) to stop listening for interactions, or alternatively delete the message, then remove your view's corresponding entry in your db
if anyone could help please ping me
One message removed from a suspended account.
Oh congratulations @hushed galleon
ty
@client.event
async def on_message(message):
# do what you did already except for comparing the id, use if message.author.id == id
and don't compare ints to strings
how do i call the stop() method the View class
self would be the View instance in your cancel_button method
One message removed from a suspended account.
so you'd write self.stop() in there
same thing that dino mentioned, just that its in the place you want it to be and not your select
Yellow color do be matching with yr pfp 👀
also that user check in each of the buttons you do can be written as an interaction_check method
@nextcord.ui.button(
label="❌", style=nextcord.ButtonStyle.red, custom_id="cancel", row=1
)
async def cancel_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
if interaction.user == self.user:
await Users.button_event(self, button, interaction)
self.stop()```
is this correct ? nothing happen
did the buttons stop responding afterwards?
One message removed from a suspended account.
well it does stop responding but I want to disable it not just stop iit
One message removed from a suspended account.
Don't delete the channel
in that case you can loop through each child in your view, set them to be disabled, then edit your message to update the view with the newly disabled components
Read what I said above
how ?
!d discord.ui.View.children
property children```
The list of children attached to this view.
One message removed from a suspended account.
loop through that, set each child's .disabled attribute to True, and use interaction.response.edit_message afterwards to edit the view
can anyone see why this is trying to send a empty embed when I'm giving it text```py
embeds = []
for item in dir(Colour):
embed = Embed(title=f"{item}", description="filler")
meth = getattr(Colour, item)
if not isinstance(meth, classmethod):
continue
embed.colour = meth()
embeds.append(embed)
self.test_log = self.bot.get_channel(847066860377342002)
await self.test_log.send(embeds=embeds)```
did you from disnake import Embed?
Dont put the id as a string. Also await the messgae.delete()
can you replace self.test_log with channel? that might fix it
Hi, is there a way to rearrange the order of the categories in the help command page? Thanks
for child in ShopButton(interaction.user).children:
child.disabled = True
await interaction.message.edit(view=ShopButton(interaction.user))```
like this ?
thats mostly right but you dont need to construct completely new Views, you already have self as the current View
Well I'm using dpy but yeah I'm importing Embed. The channel name isn't affecting it, it's the embed itself, it thinks it is empty. I would get a different error if it was unable to send to the channel
do I put it in my button_event ?
What's the full tb?
I love the disabled line
print(Embed) in the loop, to check the attributes
ooh, a rhyme
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 71, in on_ready
await self.test_log.send(embeds=embeds)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\abc.py", line 1494, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\http.py", line 501, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```
your button_event should really be broken down into each of your button methods, but theoretically you can write it there
are you trying to send an embed of each color available?
reason being that the View class handles calling the correct function for you, so you generally do not need to compare the custom_id yourself
yep, but instead of separate messages for each embed I'm using the embeds kwarg and passing it a list of embeds```py
embeds = []
for item in dir(Colour):
embed = Embed(title=f"{item}", description="filler")
meth = getattr(Colour, item)
if not isinstance(meth, classmethod):
continue
embed.colour = meth()
embeds.append(embed)
self.test_log = self.bot.get_channel(847066860377342002)
await self.test_log.send(embeds=embeds)```
can anyone help me idk how to make my bot interact with all the channels on my server
ik how to specify one
It interacts with all channels unless you messed up perms for some roles on your server
class ShopButton(nextcord.ui.View):
def __init__(self, User: nextcord.Member):
super().__init__(timeout=None)
self.user = User
self.add_item(ItemSelection(User))
@nextcord.ui.button(
label="🛒", style=nextcord.ButtonStyle.green, custom_id="buy", row=1
)
async def buy_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
if interaction.user == self.user:
await Users.button_event(self, button, interaction)
for children in self.children:
children.disabled = True
await interaction.message.edit(view=self(interaction.user))```
is this correct now ? I tried putting in my button_event function and nothing happen
i mean idk how do it
property channels```
A list of channels that belongs to this guild.
it wont react on my commands when i test it
Issue with bot's permissions on the server
What
you wrote in your buy button instead of the cancel button
How can you specify a channel for a command
Does it take it as an argument or smth
not a for a command for the bot
it cant see the commands in other channels
yes I want it to disable after press the buy button also
await interaction.response.edit_message(view=self(interaction.user))
TypeError: 'ShopButton' object is not callable
oh sure then
you dont need to call self(), just writing view=self is enough (self is already an instance and doesn't need to be constructed/called twice)
I got it now
thank you so much
i am trying to check if a category exists in my help command, but it isn't sending my message
@bot.command()
@commands.is_owner()
async def help(ctx):
e=discord.Embed(title = "Help commands", description = "Help categories", color = discord.Colour.random())
e.add_field(name="fun", value="Type in fun to see the fun commands", inline = False)
e.add_field(name="moderator", value="Type in moderator to see moderator commands", inline = False)
e.add_field(name="server", value="Type in server to see the command specific commands", inline = False)
e.add_field(name="utility", value="Type in utility to see utility commands", inline = False)
await ctx.send(embed=e)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg.content.lower() in ["fun", "moderator", "server", "utility"]
try:
msg = await bot.wait_for("message", check=check, timeout=30)
except asyncio.TimeoutError:
await ctx.send("you did not reply in time (30 seconds). type in !!help again to show up help options")
try:
if msg.content.lower() == "fun":
e2=discord.Embed(title="fun commands", color = discord.Colour.random())
e2.add_field(name="snipe", value="snipes deleted messages", inline = False)
e2.add_field(name="hack", value="This command will make it look like you are hacking someone as it was a little prank", inline = False)
await ctx.send(embed=e2)
if msg.content.lower() == "moderator":
e3=discord.Embed(title="Moderator commands", color=discord.Colour.random())
e3.add_field(name="nuke", value="This command will delete a specific channel you mentioned and recreate it but with no messages", inline=False)
await ctx.send(embed=e3)
except:
await ctx.send("this category does not exist")
Oh hek
Check this out #discord-bots message
Was wondering if you could display similar error message but with custom converters
how can i make a bot type something when a user reacts to one of its messages with a certain emoji?
Any message? Or a specific message?
Also, should it always be active?
Or should it only listen for a reaction after the user runs a command or does something?
it should be with any message and it's always active
sorry if i didn't specify this earlier
how to get guild owner’s id
shouldn't be that hard
was this the only message that was sent
I wrote a paragraph
No prob. I needed to ask those questions to see if it’s be better to use a wait for as opposed to an always listening on_reaction_add. From your answers to the questions, I think it’s be most logical to go with the latter
make an on_raw_reaction_add event, first line, check if the author of the message reacted to is your bot's user
Or the raw event too
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
reaction add has to have every message in cache
which you are not gonna do
so yeah
thank you i'm going to try this
how to get guild owner’s id
!d discord.Guild.owner
property owner```
The member that owns the guild.
so it's just guild.owner.id
Error? also please use a pastebin
i get no error at all
can anyone help
i wanted to execute the yt apply command with reaction
its cog folder btw
yt apply?
you cant fetch/get messages using Bot
idk if its a Guild method or the TextChannel, need to check
Using TextChannel*
!d discord.TextChannel.fetch_message @hasty stump
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
oh well, forgot that TextChannel has a get_partial_message method 😔
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "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.
Hi! Does anyone have an idea how to make a voice channel wich updates automaticcaly with membercount? I already have the function for member part, but not to refresh auto
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
i am confused about merging command with reaction
worked for me when i removed color=discord.Colour.random
i alr got it fixed, i had to use elif
k ig
anyone
I mean, you could use the on_member_join event
you just had to ()
This works for my bot
But not for this bot
how would i get this to find the channel name of the new made ticket and send "ticket opened"
@bot.command()
async def ticket(ctx):
guild = ctx.guild
channel = discord.utils.get(ctx.guild.channels, name=f'{ctx.author}')
role = discord.utils.get(guild.roles, name="Ticket Banned")
if role in ctx.author.roles:
await ctx.send("you cannot make tickets!")
return
await guild.create_text_channel(f'{ctx.author}')
await ctx.send("ticket made!")
await channel.send('ticket opened!')
Ratelimits. What if many members join?
No bot does that. That way is stupid
Im trying to make a statistics command, anyone know how to get the very specific linux distro? Ive tried platform.platform() but its kinda meh
That is the most common way
No way to get it to say Ubuntu 20.04 LTS Focal blah blah blah?
platform.platform(aliased=0, terse=0)```
Returns a single string identifying the underlying platform with as much useful information as possible.
The output is intended to be *human readable* rather than machine parseable. It may look different on different platforms and this is intended.
If *aliased* is true, the function will use aliases for various platforms that report system names which differ from their common names, for example SunOS will be reported as Solaris. The [`system_alias()`](https://docs.python.org/3/library/platform.html#platform.system_alias "platform.system_alias") function is used to implement this.
Setting *terse* to true causes the function to return only the absolute minimum information needed to identify the platform.
Hello, i’m using MySQL to create a database and i’m just wondering whether this would be the way to send the database, with all the information inside of it:
Tabel_1 = [
{"userid": user.id, "channelid": channel.id}, # first piece of info / aka first column
{"userid": user.id, "channelid": channel.id}, # second piece of info
# and so on...
]
Would I do this?
system_alias(platform.platform())
or
platform.platform(aliased)
This is more like #databases question
platform.platform(True)
alright thanks, i wasnt sure where to post because it relates to both 👍
guess it dont have the actual name lol
may have to get it to parse it from neofetch 
Im very OCD lol I like specifics
Oh understandable haha
!pypi distro
Prolly use this?
$ python
>>> import distro
>>> distro.linux_distribution(full_distribution_name=False)
('centos', '7.1.1503', 'Core')
i was looking at that lol
No native way to add cooldowns to buttons, you'll have to do it yourself
Store the last time they clicked in a database, next time they click, get the timedelta between now and last time they clicked (from the database), check if it's > 10 minutes. If so, do something, if else, do nothing
Thats a lot better lol thanks
Cool!
!e
import distro
print(distro.linux_distribution(full_distribution_name=False))
@sick birch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'distro'
aw
Its a 3rd party lib
Could you do it with os?
I was hoping to make it cross platform
I'm pretty that's an stdlib
using the os module
Didn't find a way, was looking at that only first
Since os means operating system and he wants to find its name
You use os.system for running terminal commands right?
Yea
But u cannot get the output
!d asyncio.create_subprocess_shell is better and non blocking
coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.
Important
It is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands...
The first bot I made is up to 4.6 star rating and 700 servers 
!e
import os
os.system("pip3 install distro")
@sick birch :warning: Your eval job has completed with return code 0.
[No output]
Haha
Damn, mine is still in 140 servers and was made like 1 year ago
im going to bot commands lol
won't work @sick birch
sad
How to make music bot with Spotify?
would've been funny
Who know?
!e
import os
print(os.uname())
@blissful sparrow :white_check_mark: Your eval job has completed with return code 0.
posix.uname_result(sysname='Linux', nodename='snekbox', release='5.10.0-13-cloud-amd64', version='#1 SMP Debian 5.10.106-1 (2022-03-17)', machine='x86_64')
You can't, the API doesn't let you
Ooh
Sad
Mines been around for about 5-6 months 
Lucky
how would i get this to find the channel name of the new made ticket and send "ticket opened"
@bot.command()
async def ticket(ctx):
guild = ctx.guild
channel = discord.utils.get(ctx.guild.channels, name=f'{ctx.author}')
role = discord.utils.get(guild.roles, name="Ticket Banned")
if role in ctx.author.roles:
await ctx.send("you cannot make tickets!")
return
await guild.create_text_channel(f'{ctx.author}')
await ctx.send("ticket made!")
await channel.send('ticket opened!')
@maiden fable lol could parse this
or output the version
Are there other ways to broadcast music?
Prolly but idk if it works with CentOS and stuff
sound cloud
Ok,i try
What the fuck
bro can someone answer my thing please?
Hm?
Channel.send is the correct way
there isnt an issue with that?
Idk, I'm still half asleep but if you're sending a message you'll need the channel object
Oh it works. Cool
MC SMP
Player Vs Enemy

And if messages aren't sending it's probably because you don't have the channel 
!e
import os
os = os.uname()[3]
print(os)
im trying to find the channel ctx.author because the bot created a channel called the authors discord name. I know it isnt an issue with channel because i changed the name of the channel in the code and it worked fine.
os.uname().version
should work
I mean my method worked too lol
Oh it did?
!e
import os
os = os.uname()[0][3]
print(os)
@blissful sparrow :white_check_mark: Your eval job has completed with return code 0.
u
Thought it didn't that is why the output isn't there lol

Lmao
!e
import os
os = os.name()[3]
print (os)
@blissful sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: 'str' object is not callable
Lol
maybe it dont like the var name
!e
import os
os_name = os.name()[3]
print (os_name)
@blissful sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: 'str' object is not callable
!e
import defined```
@dull terrace :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'defined'
!e
import os
os = os.uname()[3]
print(os)
@blissful sparrow :white_check_mark: Your eval job has completed with return code 0.
#1 SMP Debian 5.10.106-1 (2022-03-17)

!e
defined = not_defined```
@dull terrace :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'not_defined' is not defined
Like statistics?
yes
That’s not really a question for here. But look into psutil
It doesn’t
Look into the documentation
It tells you the meaning of the number and the unit it’s given in
For example I think psutil gives memory information in bytes.
Bruh what the hell of hosting do you suggested to me my domain doesn't even work 
So if you wanted to get it in gigabytes instead you’d divide the number it gives you by the amount of bytes it takes to make up a gigabyte
Personally haven't used netcup but it's in one of the pins we're migrating to the site so I can only assume it's good
Probably doesn’t have support for windows 11 then
Does it work inside docker 👀
How's it do that? I was under the impression docker was fully isolated
Unless docker passes through host info as well
Well os.uname() seems to be getting the containerized instance of snekbox
import os
print(os.uname())
Breh
import discord, os, psutil, time, platform
from discord.ext import commands
from psutil._common import bytes2human
load1, load5, load15 = psutil.getloadavg()
cpu_usage = (load15/os.cpu_count()) * 100
memory_used = psutil.virtual_memory().used
memory_available = psutil.virtual_memory().available
def minutes_elapsed():
return ((time.time() - psutil.boot_time()) / 60)
class Stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=['stats'])
async def statistics(self,ctx):
embed = discord.Embed(title='Bot/System Statistics' , color=0x000000)
embed.add_field(name='CPU', value=f'{platform.processor()}' , inline=True)
embed.add_field(name='CPU Usage', value=f'{cpu_usage}%', inline=True)
embed.add_field(name='CPU Average', value=f'{load1} \n {load5} \n {load15}')
embed.add_field(name='Server Uptime', value=f'{round(minutes_elapsed())} minutes', inline=True)
embed.add_field(name='Memory Used' , value=f'{bytes2human(memory_used)}', inline=True)
embed.add_field(name='Memory Available', value=f'{bytes2human(memory_available)}', inline=True)
embed.add_field(name='Operating System' , value=f'{platform.platform()}', inline=True)
await ctx.reply(embed=embed)
async def setup(bot):
await bot.add_cog(Stats(bot))
this works on my windows laptop but not my ubuntu server
You're running an ubuntu docker?
I think it uses i think debian slim in the container
actually idk what its using lol
looks like that
await ctx.send("", components = [
Select(
placeholder = "Select a category...",
options = [
SelectOption(label="📊 Info", value="Asyncdef"),
SelectOption(label="🏷️ Miscellaneous", value="Yoooo"),
SelectOption(label="🚀Fun", value="G"),
SelectOption(label="🛠️ Moderation", value="Wassup"),
SelectOption(label="👨💼 Server-Management", value="Yo")
]
)
])
while True:
try:
select_interaction = await client.wait_for("select_option")
await select_interaction.send(content = f"{select_interaction.values[0]} selected!", ephemeral = False)
except:
await ctx.send("something")```
This is my code for the drop down menu
It works fine but **whenever i choose an option from the drop down it loads and always says interaction failed**
Please help
Python probably has its own image
A lot of them do, I know there's one for nodejs
What lib are you using? I don't remember select_option being an event within discord.py
I just import button
and select menu stuff
I didnt use anything like nextcord or smthing
Can I see all of your imports?
Hola how are you doing today? I have a question on free bot hosting where and not replit
Sure
from discord_components import DiscordComponents, ComponentsBot, Button, SelectOption, Select
@sick birch These are the imports i did for select menu
Didnt download anything
Are they using discord.py?
Why are you using discord_components
I have never heard of discord_components
discord.py has built in dropdown menus there's no need to use bad third party libraries like discord_components
Then what do you recommend I change it to
How to get the guild ID of every server my bot is in and append it to a list?
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
The guild’s ID.
discord.py's native dropdowns
ids = [x.id for x in bot.guilds]
thanks
Could you tell me what do I import?
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
this is the class, there are multiple ways of using it
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py Here's an example I wrote myself :)
oh nvm
Oh thanks
Let me have a look
@sick birch Oh you used the class and ui.select right
How to send an embed using nextcord Interaction?
Is it the same interaction.response.send_message(embed = embed)?
@sick birch It says discord attribute has no component ui
do I have to import ui?
how to auto remove reaction when user react once
can you tell me
!d discord.Reaction.remove
await remove(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove the reaction by the provided [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") from the message.
If the reaction is not your own (i.e. `user` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `user` parameter must represent a user or member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
from on_raw_reaction_add
like that
when they will react, it will execute and remove the reaction
well until it will not work it will not be good 
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
i can access the website through the hosting domain but i can't access to it by my domain
WTF DOES THIS MEAN?
Prolly wrong config
I mean, you could get the message every time someone reacts, remove its reactions
Yea, making an API Call everytime? Sure!
actually, giving more data on a datatype like this

that would suck
Yea
I mean, it would be fun!
Ofc
How do we calculate how long a function took to respond
Nope checked it again bot domains point to the same ip 
Did u try setting redirection rules? Idk
bruh technically an hosting should do it automatically
man it would really be easier a VPS 
I said so but uhhhhhh
hahahaha i should've trusted you
OH i found the issue
the ||fucking|| SSL certificate
||what could have gone worse||
man due to my logs i started working on it at 03:50PM
is discord.py outdated
I'm pretty sure yeah
you would need to use a fork
oh what should i use
Hi I have a problem. What I'm trying to do is to get my customers' discord id from my website (set in my database) and then make my discord bot give them a role on my server. Has anyone got an idea how I could achieve it?
Nah its development has started again
No
No again
No
did you need to ping me both times
bc every time i import it it doesnt work
did you install it
Yes
terminal
oh ok
What are you trying to install?
How did you install it?
pip3 install discord.py
well
when i type in message it doesnt autocomplete
it just imports another module
like mesages import
from email import messages
i dont want that
i just want the auto complete for my vscode
Ik VSC is weird for that
oh
Happens with me too, I don't think u can do anything
oh
I want to put a function in the bot's command, in which the bot waits, either "end" is the end of the command, or two numbers (this function should work until the user enters "end")
How to do it?
i have does the same thing
@slate swan Tho u should ask in #editors-ides for a clearer answer
wait.....you cant have an on_message inside a command.......?
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
I know that
I was thinking how to solve the problem
yes you can
just have a wait_for
they do the same thing
how can i check for a certain user role in a command? using hikari btw
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
I thought you meant
@bot.command()
async def my_command(...)
@bot.event
async def on_message(...):
...
...
``` lmao
nested functions, no.
im using hikari tho
ah well idk
api call?
oh..
Thx
https://caught-lackin-in-8k-by-cyberghost.cf/FSF3cubB
def processor_name():
if platform.system() == "Windows":
return platform.processor()
elif platform.system() == "Darwin":
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
command ="sysctl -n machdep.cpu.brand_string"
return subprocess.check_output(command).strip()
elif platform.system() == "Linux":
command = "cat /proc/cpuinfo"
all_info = subprocess.check_output(command, shell=True).strip()
for line in all_info.split("\n"):
if "model name" in line:
return re.sub( ".*model name.*:", "", line,1)
return ""
embed.add_field(name='CPU', value=f'{processor_name()}' , inline=True)
help plss
?
oops forgot imports
!e
import platform, os , subprocess, re
def processor_name():
if platform.system() == "Windows":
return platform.processor()
elif platform.system() == "Darwin":
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
command ="sysctl -n machdep.cpu.brand_string"
return subprocess.check_output(command).strip()
elif platform.system() == "Linux":
command = "cat /proc/cpuinfo"
all_info = subprocess.check_output(command, shell=True).strip()
for line in all_info.split("\n"):
if "model name" in line:
return re.sub( ".*model name.*:", "", line,1)
return ""
print(processor_name())
@blissful sparrow :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 17, in <module>
003 | File "<string>", line 11, in processor_name
004 | File "/usr/local/lib/python3.10/subprocess.py", line 420, in check_output
005 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
006 | File "/usr/local/lib/python3.10/subprocess.py", line 501, in run
007 | with Popen(*popenargs, **kwargs) as process:
008 | File "/usr/local/lib/python3.10/subprocess.py", line 966, in __init__
009 | self._execute_child(args, executable, preexec_fn, close_fds,
010 | File "/usr/local/lib/python3.10/subprocess.py", line 1842, in _execute_child
011 | raise child_exception_type(errno_num, err_msg, err_filename)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/tuladahebi.txt?noredirect
hmm thats why it didnt work
I have trouble with making an "add role" command in discord.py. I don't know what is wrong; it just doesn't work.
@client.command()
@commands.has_role("Admin")
async def addrole...
breh
that's not what I need, I know how to assign roles but I need to soomehow sync it with my website
am i right in thinking pass_context=True is ignored now?
Yes
great can remove that from the code then
@command
async def start_on_message(ctx):
while True:
await bot.wait_for('message')```
yeah same same
No
if I add anther class to the same cog file do I have to add it to the setup at the bottom?
U use only one setup function and just add another line to add the cog
Yeh thats what I meant
mhm?
why are you showing the command deco like that
our friendly command deco
how do i set a function to be executed when an invalid command is execute din hikari
our beloved
Help me
Moment
cogs/music.py
from discord.ext import commands
class Radio(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self, ctx):
channel = ctx.author.voice.channel
if ctx.author.voice != None:
channel.connect()
await ctx.send('Successful')
else:
await ctx.send('Pls join to voice channel')
def setup(client):
client.add_cog(Radio(client))```
import os
from discord.ext import commands
client = commands.Bot(command_prefix='+',help_command=None,activity=discord.Game(name='Дристаю толчёк 24/7'))
@client.event
async def on_ready():
print('Bot online')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
token = os.environ.get('Token')
client.run(token)```
Sad
how do u allow a command to be ran both in guild and dms?
would it have to be an if statement?
hey im pretty dumb founded, i was wondering how to start a bot once you opt into the folder through cmd?
just do main.py
here is my code
import requests
import time
import logging
import ctypes
import os
from threading import Thread
from colorama import Fore
kernel32 = ctypes.windll.kernel32
tokens = open("data/token.txt", "r").read().splitlines()
logging.basicConfig(
level=logging.INFO,
format=f"{Fore.GREEN}[{Fore.RESET}!{Fore.GREEN}] {Fore.RESET}%(message)s{Fore.RESET}",
)
class Discord:
def check(token):
headers = {
'Authorization': token,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Accept': '*/*',
}
r = requests.get(f'https://discord.com/api/v9/users/@me/library', headers=headers)
if r.status_code == 200:
logging.info("Token Validated!")
print()
else:
logging.info("Token Invalid")
time.sleep(5)
def report(token, channel, guild, message):
global checked
checked = 0
headers = {
'Authorization': token,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Accept': '*/*',
}
json = {
"channel_id": channel,
"guild_id": guild,
"message_id": message,
"reason": reason
}
while True:
r = requests.post("https://discord.com/api/v9/report", headers=headers, json=json)
if r.status_code == 201:
ctypes.windll.kernel32.SetConsoleTitleW(f"[REPORT BOT] | %s" % checked + ' SENT')
checked += 1
logging.info("Report Sent Successfully!")
else:
print(Fore.RED + "[" + Fore.RESET + "!" + Fore.RED + "]" + Fore.RESET + " Error Sending Report!")
def get_reason():
print(f"""{Fore.GREEN}[{Fore.RESET}{0}{Fore.GREEN}]{Fore.RESET} Illegal Content
{Fore.GREEN}[{Fore.RESET}{1}{Fore.GREEN}]{Fore.RESET} Harassment
{Fore.GREEN}[{Fore.RESET}{2}{Fore.GREEN}]{Fore.RESET} Spam or Phishing Links
{Fore.GREEN}[{Fore.RESET}{3}{Fore.GREEN}]{Fore.RESET} Self-Harm
{Fore.GREEN}[{Fore.RESET}{4}{Fore.GREEN}]{Fore.RESET} NSFW Content
""")
while True:
reason = input(Fore.GREEN + "[" + Fore.RESET + "?" + Fore.GREEN + "]" + Fore.RESET + " Reason >> ")
if reason in list('01234'):
return reason
print(Fore.RED + "[" + Fore.RESET + "!" + Fore.RED + "]" + Fore.RESET + " Invalid Reason!")
print()
if __name__ == '__main__':
os.system('cls')
reason = Discord.get_reason()
for token in tokens:
Discord.check(token)
guild = input(Fore.GREEN + "[" + Fore.RESET + "?" + Fore.GREEN + "]" + Fore.RESET + " Guild ID >> ")
channel = input(Fore.GREEN + "[" + Fore.RESET + "?" + Fore.GREEN + "]" + Fore.RESET + " Channel ID >> ")
message = input(Fore.GREEN + "[" + Fore.RESET + "?" + Fore.GREEN + "]" + Fore.RESET + " Message ID >> ")
print()
for i in range(250, 1000):
Thread(target=Discord.report, args=(token, channel, guild, message)).start()
pip install requests
yup
ah yes your code
you wrote all of that yet u don't know how to run a file
@velvet compass sorry for the ping but i saw you chatting in general so it shouldn't matter; this dude is asking for help with code against tos very abdly
A Discord report bot?
my friend did
yeah
no he didn't, it's from github made by dropout
yeah thats my friend
What is this used for?
so im able to report people in my server
what
suppose someone is posting gore or inapporpriate things
do u know the point of this tool
You can do this manually
is someone in trouble 
This is not appropriate language for this server
How would I make a command where if someone does .massnick {name} it changes there nickname in all discords the bots in.

api abuse
u can just iterate through all members in a guild and just change nicknames
for member in ctx.guild.members:
await member.edit(nick=add_an_arguement_to_your_command)```
don't use that tho, since it's api abuse and very high chance your bot could be banned
It’s only in a few discords, it’s convenient instead of going into each discord and manually doing it

I don't think that's what he meant
ohh i miss read my apologies
iterate through the servers the bot's in, get the member with that id and use the member.edit line
so get_member might be None, check for that
so he wants the authors nickname to be changed everywhere?
yeah
rather than sending the GIF with the embed, send the link outside the embed
help me pls
Hello there, so I have a discord bot and in a json file I have roles able to run some commands. I use the following line of code to check the role or permissions of a user:
if (ctx.message.author.guild_permissions.administrator) or (any(r.id in self.idroles for r in member.roles))
But for some reason, the bot says that permissions is missing despite having the role. Putting the role on top of all of the others solve the issue. But I don't want to do that with every role. So would there be a way to fix this?
and for some reason even after doing so it still misses the permissions. By restarting the bot it suddendly works
It's a bit confusing
in message event, check if the message content has your bot mentioned in it, then do your stuff
it might be a type issue
id_user = str(ctx.message.author.id)
member = ctx.author
self.idroles = map(int, self.idroles)
if (ctx.message.author.guild_permissions.administrator) or (any(r.id in self.idroles for r in member.roles))``` but I don't see what could be wrong
getting the weirdest bug right now
i have drop downs that appear under certain conditions, the placeholders are stuck on old ones and show the same for every time they appear
but it only happens on mobile
and when viewing the same drop downs on desktop it shows the correct placeholders
re-opened discord on mobile and it updated them to the correct ones
now it's working right wtf
reset the game and getting the same bug
but when i view the exact game on desktop it's the correct thing
How to make cogs in version 2 after update ?
but i want it to be embeded
Hey I can't figure out what member.roles return, is it a list of name or id ?
import discord
from discord.ext import commands
class Radio(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self, ctx):
channel = ctx.author.voice.channel
if ctx.author.voice != None:
await channel.connect()
await ctx.send('Successful')
else:
await ctx.send('Pls join to voice channel')
def setup(client):
client.add_cog(Radio(client))
You forgot to add await in this line: channel.connect()
it returns a list
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
ookay so i think the bug is that whatever was last selected in a dropdown stays as its placeholder
but only on mobile for some reason
and only temporarily, once you reload it goes to the actual placeholder
sooo how do i fix it
okay but is it the name (str) or id (int) ?
?
what that mean
int doesn't have any id attribute I assume you're trying to get the id out of an int
discord has actually screwed my app so bad
role objects
role is an int and not a role object
Bug visuals for mobile Android. It's fixed when you reopen discord or look at it on mobile. Any ideas on how to get around it?
sorry for the long message, idk how to post this without it 
this is after selecting materials market, now everything uses that as the placeholder...
damn nice
gonna be a horrible experience for anyone on mobile and rn its looking like a discord bug that wont be fixed for months
You leaked your token, I suggest you reset it immediately
its my old token lol
do you know why it isnt working tho
Can I see the client constructor?
Did you save the file
yea
hmmm
The error at the bottom is different
It doesn't say client isn't defined
oh
ah
no one has any ideas? This is literally the last thing i need for my bot before it's beta ready... 
You said that token was your old token right
nope i just updated it and im gonan reset it rn
So it makes sense that it's an invalid token
And that's the token you're using?
ye
ima just uninstall and stop trying
Could you show BotBase?
lol
that's not so good innit
@sick birch im trying every single WAY
are you using discord.py or pycord?
have you got discord.py installed? and the correct version?
yea
yeah i do
i just reinstalled ithttps://gyazo.com/ee21e35cb3fa9f1ddad8d92342b8524b
maybe try switching over to pycord, it’s basically the same
kk
- Uninstall
discord.pyor any other forks of discord.py you might have with the namespacediscord.
python -m pip uninstall discord.py discord -y
- Install
py-cord
python -m pip install py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Updating to beta:
pip install py-cord==2.0.0b5
you have two on_ready() functions
^
how can I solve that?
remove one on_ready function
or do I need to create a new @client.event?
no, you cant have two on_ready events
will both things work? Or will 1 thing stop
send your code
oh, so I need to delete 1?
yes
oke wait
just the on_ready parts
@client.event
async def on_ready():
print("[Connected]")
activity = discord.Game(name="protecting gako's server", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
async def on_ready():
print(f'{client.user} has connected to Discord!')
verificationChannel = client.get_channel(verificationChannelID)
messages = await verificationChannel.history(limit=200).flatten()
for message in messages:
print(message.author)
if str(message.author) == botName:
await message.delete()
button = Button(label="Verify")
view = View()
view.add_item(button)
button.callback = send # 'send' voor modals , button_callback voor button only verification
await verificationChannel.send("Enter the password to verify!", view=view)```
why do you have buttons with your on_ready event
Only the second one, I created a verification system but I also want to add the playing game thingy
dyk python or u just wanna make a discord bot
remove the on_ready part after the activity=activity
https://git-scm.com/download/win is this legit
what is it?
what’s Git? is it GitHub?
yh
!paste
Pasting large amounts of code
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ERROR: Error [WinError 2] The system cannot find the file specified while executing command git version
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH? i got this eror i searched nd this came
yes
anyone here on mobile want to quickly test a bot?
i’m on mobile
same
sent you a friend request
an embed doesn't count as empty if it has a field in it right? or do I need to have a description?
thanks for testing my bot sift
👍
is there any way to like resync all the global slash commands cause all the servers my bot is in slash commands come up in the / context menu but in my server it doesnt?
@sick birch do you think you can help me again? I started fresh and removed all the messed up code i had before
Sure, remind me what you were trying to do?
bots can only send 5 messages per second within a guild right?
It's not 5/1s
It's 5/5s
And this endpoint has ratelimits utilising buckets
So there would be different ratelimit counts per channel, etc
Yeah, sure. Shouldn't be that difficult, follow this framework and you should be good:
@bot.command()
async def my_command(...):
message = await bot.wait_for(...)
if "@gmail.com" in message.content:
# user sent a message with "@gmail.com" in it
else:
# they didn't do something
sorry if this seems dumb but im still trying to understand, what would i put in wait for() or my command?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Ok thanks, what would i put in the my command
breh
def get_prefix(bot, ctx:ctx.commands):
c.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id TEXT,prefix TEXT)')
c.execute(f'SELECT prefix WHERE GUILD_ID = {ctx.guild.id}')
result = c.fetchone()
if result:
prefix = str(result[0])
if not result:
prefix = '.'
return prefix
gives this error def get_prefix(bot, ctx:commands.ctx): AttributeError: module 'discord.ext.commands' has no attribute 'ctx'
oh wait nvm ik what I did I think
So, i have a timestamp that looks like 2018-11-25T18:00:55.000+0000 - is it possible to change it to a new string that converts and outputs 25th November 2018 in any way?
thanks
thats not a timestamp but yes
Its part of my discordbot, i just added the whole date in the embed, but that looks absoluty weird, so i just want to convert it to some kind of easier date.

so I have this as part of my on_voice_state_update logs ```py
values = []
message = ""
if before.mute != after.mute: # Member muted/unmuted
values.append(f"{'Unmuted' if after.mute is False else 'Muted'}"),
embed.colour = (
Colour.dark_teal() if after.mute is False else Colour.dark_magenta()
)
if before.deaf != after.deaf: # Member deafened/undeafened
values.append(f"{'Undeafened' if after.deaf is False else 'Deafened'}"),
embed.colour = (
Colour.dark_teal() if after.deaf is False else Colour.dark_magenta()
)
if before.self_mute != after.self_mute: # Member self-muted/unmuted
values.append(
f"{'Unmuted' if after.self_mute is False else 'Muted'}",
)
embed.colour = (
Colour.dark_green() if after.self_mute is False else Colour.dark_red()
)
if before.self_deaf != after.self_deaf: # Member self-deafened/undeafened
values.append(
f"{'Undeafened' if after.self_deaf is False else 'Deafened'}"
),
embed.colour = (
Colour.dark_green() if after.self_deaf is False else Colour.dark_red()
)
if before.self_stream is not after.self_stream:
values.append(
f"{'Not-Streaming' if after.self_stream is False else 'Streaming'}",
)
embed.colour = (
Colour.dark_green() if after.self_stream is False else Colour.dark_red()
)
if before.self_video is not after.self_video:
values.append(
f"{'No Video' if after.self_video is False else 'Video'}",
)
embed.colour = (
Colour.dark_green()
if after.self_video is False
else Colour.dark_green()
)
if before.suppress is not after.suppress:
values.append(
f"{'Not Suppressed' if after.suppress is False else 'Suppressed'}",
)
embed.colour = (
Colour.dark_teal() if after.suppress is False else Colour.dark_magenta()
)
if before.requested_to_speak_at is not after.requested_to_speak_at:
values.append(
f"<t:{int(after.requested_to_speak_at)}:R> ",
)
embed.colour = Colour.dark_blue()
for value in values:
if value is values[0]:
message = message + value
else:
message = message + f"\n{value}"
if message is not None:
embed.add_field(name="Additional Information", value=message)but for some reason it's giving me this errorpy
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 269, in on_voice_state_update
await self.test_log.send(embed=embed)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\abc.py", line 1494, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\http.py", line 501, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required```and I'm not sure why since it shouldn't be trying to add the field if the message is empty/None
Alright, thanks alot!
Use a pastebin pls
Bot aint replying now, all I did was try to add a db.
@bot.event
async def on_guild_join(guild):
await guild.create_role(name="Ghosted" , color=0x020101)
conn = sqlite3.connect('./sql/ghost_bot.db')
c = conn.cursor()
c.execute(f'SELECT * FROM ghost_bot WHERE guild_id = {guild.id}')
result = c.fetchone()
if not result:
c.execute('INSERT INTO ghost_bot(guild_id,prefix) VALUES(?,?)', (guild.id, '.'))
if result:
c.execute(f'UPDATE ghost_bot SET prefix = ? WHERE guild_id = ?', ('.', guild.id))
conn.commit()
c.close()
conn.closes()
no errors in the console
def get_prefix(bot, ctx:commands.Context):
conn = sqlite3.connect('./sql/ghost_bot.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS prefixes(guild_id TEXT,prefix TEXT)')
c.execute(f'SELECT prefix WHERE GUILD_ID = {ctx.guild.id}')
result = c.fetchone()
if result:
prefix = str(result[0])
if not result:
prefix = '.'
conn.commit()
c.close()
conn.close()
return prefix
@slate swan @boreal ravine well it's an error and then some code, it's not 'large' but any means but since it offends you here's a pastebin link: https://paste.pythondiscord.com/buvokuvafa
bot = commands.Bot(command_prefix='get_prefix', intents=intents)
def get_prefix(bot, ctx:commands.Context):
conn = sqlite3.connect('./sql/ghost_bot.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS ghost_bot(guild_id TEXT,prefix TEXT)')
c.execute(f'SELECT prefix WHERE guild_id = {ctx.guild.id}')
result = c.fetchone()
if result:
prefix = str(result[0])
if not result:
prefix = '.'
conn.commit()
c.close()
conn.close()
return prefix
Yes please, even on a desktop monitor it takes up a full screen and then some more, let's be more considerate towards our laptop and mobile friends
SELECT prefix FROM prefixes WHERE guild_id = 123
``` try this?
also if you aren't familiar with SQL you can use an ORM
now it aint replying
error?
no errors
new code?
def get_prefix(bot, ctx:commands.Context):
conn = sqlite3.connect('./sql/ghost_bot.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS ghost_bot(guild_id TEXT,prefix TEXT)')
c.execute(f'SELECT prefix FROM ghost_bot WHERE guild_id = {ctx.guild.id}')
result = c.fetchone()
if result:
prefix = str(result[0])
if not result:
prefix = '.'
conn.commit()
c.close()
conn.close()
return prefix
bot = commands.Bot(command_prefix=get_prefix, intents=intents)
Im learning SQL since its not too hard
I would use aiosqlite but I need to understand where I should put the awaits lol
this is to just get me up n running
how to make a command that adds a word or phrase to a list in a seperate file like a json file or smth
try putting conn.commit below where you create the table
it might not create the table
I mean it has created it cos I deleted the file and it made it again with the two columns
ill give a go anyways
nope same result
silent af
how do I feetch a role by Id and give it to the command user?
lol
im pretty sure i have a working role command set if you want i can go find the code for it
if you want to sure
kk, can you DM me?
sure
@bot.event
async def on_message_join(member):
channel = bot.get_channel(961059290058227765)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)```
btw @silent ermine still needs help i misunderstood the question
^
role = guild.get_role(ROLE_ID) # guild = the discord.Guild object
await ctx.author.add_roles(role)
thank you
You can fetch a role by ID using:
await guild.fetch_role(id)
You can give that role using:
await member.add_roles(role)
kk
good thing its not
why is that
and why cant i use it
i want it back bcs i need slash commands for my bot
no
why
i see no reason why not to use main. too hard? theres examples in the github repo.
you will when erros come in your way
You won’t be able to use it when u upgrade to discord.py v2
im using it for a very tiny simple 1 server bot
It's strongly recommended to not use the old third party libraries and rather use the mainstream and maintained forks that are full featured
just use main?
It's still easier to use main, since you have everything in one
Yeah, fair point
you do you
i will definitely look into it but for now im sticking with what i know how to use
you can learn main in the examples in the repo(if there is) or just read src!
src?
source code
ok
And the documentation
i assume they have examples in docs
Yeah, I'm with you on that one
i use disnake because i like the simple slash command impl
You know I don't really get why these libraries are implementing slash commands in a way that it runs every time you run your bot
which it feels idk better since the slash commands are bound to your bot and not a tree
I prefer discord.js's implementation
smh
Deploy once, listen in your bot, seperation of concerns
I'm just saying it's not logical to bundle slash command registration with listening
For regular text-commands I understand
But slash commands in their nature are persistent
i tried js once, never ended up sticking to it
I guess they're getting too caught up in trying to make the transition as seamless as possible but neglecting the fact that it may not fit with the current implementation
Yeah not the best experience there
I prefer it over here tbh
i dont really like how people get treated in the dpy server its quite shamful
this server has been the best i've found for discord bot info so far 
disnake has been pretty chill too when i have an issue
What's so wrong with it
seems like you havent visited before?
I have
i like disnakes server. its quite professional and helpful and its owner is quite a cool person which ive spoked to him before, i had a lovely conversation with him and the libs helpers are cool people as well, very nice people from my experience. Yes some arent as nice but they arent hateful in anyway.
they think people dont make mistakes smh
Fair amount of gatekeeping
btw dont you have to wait a while before slash commands update?
An hour for globals, yes. Instant for guild
they mostly judge by roles which i hate theres just this big higherarchy
ok nice
but they still work instantly in DMs with bot right
at least with discord_slash
they do
Doubtful
ok
bro
yeah im using global im pretty sure so that would make sense
we just judge the dpy server and you just recommend it💀
he didnt recomment it, he asked in it
anyone else wanna do a little beta test of my bot? 
just have an alt account
I just realize kayya is yerlikaya
lmfao
it's a game bot
same😔
I was like treating him like a new person
im not because i have him added😳
1 fps😳
I also have him added
💀
His eren avatar threw me off
🗿
depends how fast you click
I finally got a bank account yesterday
not really
We don't talk about that time
its not quite fps
😳
as you arent getting the same frames each second
sure
Can i also try
sure sure
do you use a db to store progress?
How else would he
Bro
my ctrl bind is on stand by
im down
havent tried it so im down to try something new
game engine?
if not game:
await make_game()
bro
whats the game name?
how about a user who is already in a game and tries to create another one
TypeError: make_game is not a coroutine
i see..
Xiangqi probably
andy i still recognize you😳
for drop downs do we have to import anything?
just some classes
Kind of weird
I'm down i don't know how much i can help or if i can though
no, only cuz your nickname in rin is andy lmfao
Kind of weird you check that
dont question my reasons!
only if GitHub connections was not a thing
I can tell that's andy because of my note
also is there a way for the bot to send the current guild prefix when mentioned?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
Check if the bot.user is in this
!d discord.ext.commands.Bot.get_prefix , use this to get prefix
await get_prefix(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to with the message as a context.
Changed in version 2.0: `message` parameter is now positional-only.
I got no clue if i can help with that
async def make_game():
await code_the_game()
next step in the source code
Lmao impostor variable
the file structure is horrible and 2 classes in the same file is just something else
you guys have any feedback on the game? 
i mean since its base ig
You made Grid a generic by inheritance, but you also don't give any typevars to it? Your repr also does an O(n * m) call everytime, And you have a coroutine function find that does an atomic operation
This makes no sense
yeah theres allot of useless coroutines for some what reason
get_deployable is also pretty in-efficient
@bot.event
async def on_mention(ctx, user: discord.Member):
prefix = await get_prefix()
embed = discord.Embed(title='Guild Prefix', description=f'{user.mention} the current prefix is {prefix}', color=0x000000)
await ctx.message.reply(embed=embed)
Bot aint replying wid da prefix, I do summin wrong?
async def get_prefix(bot, ctx:commands.Context):
conn = sqlite3.connect('./sql/ghost_bot.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS ghost_bot(guild_id TEXT,prefix TEXT)')
c.execute(f'SELECT prefix FROM ghost_bot WHERE guild_id = {ctx.guild.id}')
result = c.fetchone()
if result:
prefix = str(result[0])
if not result:
prefix = '.'
conn.commit()
c.close()
conn.close()
return prefix
get_prefix()
https://github.com/Tebbtz/probable-lamp/blob/5801df4e1616b1d89d661b6cf4f38aff0eae4fdb/main.py#L92-L102 this, you for some reason make a whole new list for each exisiting offset
main.py lines 92 to 102
neighbors = []
for pair in ((0, 1), (0, -1), (1, 0), (-1, 0)):
if (
0 <= imposter[0] + pair[0] <= len(matrix) - 1
and 0 <= imposter[1] + pair[1] <= len(matrix[0]) - 1
):
neighbors.append(matrix[imposter[0] + pair[0]][imposter[1] + pair[1]])
self.deployables = {
key: value for key, value in self.mappings.items() if key in neighbors
}```
Then you iterate the list again after creating it
Also please note, as I said in my first message, everytime you call your __repr__ it's an O(n * m) call 👁️ 👁️
So, this would happen when you call print with no __str__ bound, and other stuff
for i in range(1000):
for idx in range(1000):
...
``` basically
You can see how that would be computationally expensive
Well why are you casting the dict back to a list?
Couldn't you just iterate values() or something
In your repr
main.py line 26
_repr_list = list(self.mappings)```
You cast it to a list, so that would be O(n) then you iterate it again
When you could've just iterated keys in the first place
Which has me confused, as to why even cast in the first place
It makes 0 sense
I would also recommend getting rid of setting the event policy to windows, that would break things for linux users. Espcially if you put it module level
I overall would recommend and even suggest going back to the drawing board and really thinking about what to write
You should try to write proper code, not in the spur of the moment code
i just read a bit of src while andy got to the core of everything😭
@slate swan are you using 3.10?
what
^
anyone?
main.py lines 68 to 72
async def find(self, key: KT, *, default: KT = "") -> VT:
try:
return self[key]
except KeyError:
return self[default]```
Could just be return self.get(key, "")
I would also recommend finding a way to render the board yourself without tabulate
I'm sure it adds some more overhead you wouldn't really need
Alright, that's good
Also keep in mind, asserts shouldn't be used for public code or whatever like that
on_mention isnt an event that exists in dpy, you'd have to handle on_message and compare the message content manually to know if they purely mention your bot (i.e. equal to either @balmy crown or @balmy crown)
also you forgot to pass any parameters to get_prefix()
Make sure to remove it later on if you are using it as a placeholder

Your main meat is gonna be in the get_deployables, I'd start rewriting that
Also is there any need to make it async??
Most, if not all of your calls are atomic operations
If you make the iteration asynchornous, which is super easy
You'd have to pretty much make everything else async
which makes no sense here
Once you have async somewhere in your codebase, it pretty much infects the whole
tabnine do be misleading 

You don't
Just make it synchronous, there is no real reason for you to make it asynchronous
what do you guys even mean on atomic operations?
You gonna give yourself a headache, and it's probably not even gonna make your code any better speed wise
just make a function a coroutine if it actually needs something async inside of it
^
If you want to use it in your discord bot
Just run it inside of executor
Or, to_thread
!d asyncio.to_thread
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were ran in the main thread. For example:
2 + 2 would be an atomic operation
It's like doing:
async def adder(num1: int, num2: int):
return num1 + num2
There's no point in doing that
And a lot of calls are atomic, like nullptr mentioned
you mean useless functions?
For example print()
Yes, I'm demonstrating a concept
thats andy lmfao
same person
yeah you couldve used sum if you wanted to use a function
😔
or was it
😅
Been seeing around lately a common missconception is making a function a coroutine function will suddenly just make it asynchronous and not blocking
can you use custom emotes inside these drop downs?
https://caught-lackin-in-8k-by-cyberghost.cf/iZfQGSs6
how so?
@slash.slash(name="Sign", description='Sign a player to a team')
@has_any_role('Franchise Owner', 'General Manager', 'Head Coach', 'Assistant Coach')
async def sign(ctx, team: discord.Role, *, user: discord.Member):
await user.add_roles(team)
embed = discord.Embed
embed = discord.Embed(title="Signing Completed", description=f" {team.mention} Signed {user.mention}")
embed.add_field(name= "**Coach** {ctx.author.mention}", inline=False)
embed.set_author(name=f"{ctx.author}", icon_url=str(ctx.author.avatar_url))
await ctx.send(embed=embed)
role2 = ctx.guild.get_role(961079410050605106)
await user.remove_roles(role2)```
What do you mean how so
like how would it not block exactly?
I’m not saying it won’t block, I’m saying the opposite

