#discord-bots

1 messages · Page 141 of 1

faint basalt
#

I'm trying to get started, so which wrapper would be better, discord.py vs pycord?

slate swan
pulsar bridge
#

Is there a way to check what channel a bot has been invited to when it joins a guild?

#

Nevermind! I think I've found a solution

slate swan
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

"breach terms of services"

#

if something works, it doesn't mean that its right thing to do

loud junco
#

it will but if someone else got your project source they will have your bot token

slate swan
#

try it and see

loud junco
#

and they will do bad thing with your bot

#

such as sending weird pictures that we all know

shrewd apex
#

lol

potent light
#

What does this refer to:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In type: Value must be one of {4, 5, 6, 7, 10}.
I am trying to use this:
await interaction.response.send_modal(Questionnaire2(self.form_data, self.view, self.username_view, self.form_names)) inside Questionnaire2().

#

Where can I find the reference to all form body with their value things?

slate swan
potent light
# slate swan can you show us the code please?
class Questionnaire2(Modal, title = "Questionaire Response"):
    def __init__(self, form_data, view, username_view, form_names):
        super().__init__()
        self.form_data = form_data
        self.username_view = username_view
        self.view = view
        self.form_names = form_names
    name = TextInput(label='Type a profile name here', custom_id = "form_name")

    async def on_submit(self, interaction: discord.Interaction):
        answer = interaction.data["components"][0]['components'][0]['value']
        if answer not in self.form_names:
            self.form_data[interaction.data['components'][0]['components'][0]['custom_id']] = answer
            await interaction.response.send_message(view = self.view, ephemeral=True)
            await self.view.wait()
            self.username_view.stop()
        else:
            await interaction.response.send_modal(Questionnaire2(self.form_data, self.view, self.username_view, self.form_names))```
#

Error in the last line.

slate swan
potent light
# slate swan show the slash or normal command too

It has dozens of lines, here is the callback though:

async def newusername_callback(interaction):
            print("usernames", form_names)
            await interaction.response.send_modal(Questionnaire2(form_data, view, username_view, form_names))
            await view.wait()
            username_view.stop()```
slate swan
#

last line is not ok tho 💀

potent light
naive briar
slate swan
#

why u addewd 2 datas

#

interaction.data['components'][0]['value']

slate swan
potent light
#

It's not that important.

slate swan
potent light
slate swan
#

send a button that sends a the modal as response

#

you can check for if the name that he answered is exist or not

#

if not u send an ephemeral message with a button retry ans send that same modal again

potent light
slate swan
#
if str(self.name) == "Exist name or a list of names":
  
  await interaction.response.send_message("This name exist already! Click the retry button below to add a new name.", view=yourretrybutton(),ephemeral=True)
#

@potent light like dat ;] here's an quickkk example

slate swan
#

you're welcome.

drifting arrow
#

How do I remove a button from a message?

#

I want to make it so when someone clicks a button the original message is edited and the button is removed

unkempt canyonBOT
#

@marsh pollen :white_check_mark: Your 3.11 eval job has completed with return code 0.

['-', '-', '-', '-', '-', '-', '-', '-', '-', 's']
slate swan
drifting arrow
slate swan
#

Np

limber pagoda
#

How do you pronounced ephemeral

#

Is it ee-FEE-mur-al

#

Or eh-FEE-mur-al

#

Or other?

static oak
#

Hi, I really want to hear the opinion of an experienced programmer on my code. I don't have anyone near me that could do that, but I couldn't find anywhere in the rules that I am not allowed to do this in the help channels. Still, I thought I'd ask here first. It really isn't a big piece of code, it's just that I want to improve on it if I can.

slate swan
#

Post it here and people will hop in to help if they can

slate swan
#

but it probably doesn't matter exactly how your say it :)

short pulsar
#

how make ban command i ben trying so hard

slate swan
#

Personally I wouldn't bother with making yet another bot for commands such as banning/kicking members. The built-in options on Discord can do that perfectly fine and so can much larger, trusted bots such as Dyno. But if you really wanna go for it, Guild.ban is probably what you're after.

sage otter
#

why are you discouraging people to make bots in a a channel meant to help people in making them. 💀

vale wing
#

It's eifemeral

slate swan
short pulsar
slate swan
short pulsar
#
@bot.tree.command(name="my-command", description="Command desc")
async def slash(ctx):
  await ctx.send("hello!")
#

that would be so much easier

slate swan
#

As slash command is positional only. you can use ctx

#

but as it's a response you can't do ctx.send() you have to do ctx.response.send_message()

short pulsar
#

omg

upbeat otter
#

😳

slate swan
#

It uses ctx.edit or ctx.send xd

maiden fable
#

That's.... bad

sage otter
slate swan
#

Docs exist

short pulsar
brittle ocean
#
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1.choices.5.name: This field is required

what does this even mean?

slate swan
#

the choice should have a name

brittle ocean
#

k thx

brittle ocean
#
@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
    interaction: Interaction,
    user: nextcord.User = SlashOption(
        required=True,
        name="user",
        description="The user to remove the infractions from",
    ),
    remove=SlashOption(
        required=True,
        choices=str(clrinfr),
        name="removeall",
        description='put in "all" or 1-10 or a power of 5',
    ),
):
    if remove == "all":
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount="all"
        )
        embedr = nextcord.Embed(
            color=nextcord.Color.blurple(),
            title="Alle overtredingen van {interaction.user} zijn verwijderd!",
            description="Tip: je aan de regels houden werkt echt!",
        )
        await interaction.response.send_message(embed=embedr)
    elif remove == 0:
        return ValueError
    elif remove == int > 0:
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount=remove
        )

here's the code

slate swan
#

i don;t think thats how choices argument work in SlashOption work

brittle ocean
#

what do you mean?

slate swan
#

how do i make my entire dropdown so that users cant interact with it once a option is clicked?

slate swan
maiden fable
#

max_values kwarg

#

!d discord.ui.Select.max_values

unkempt canyonBOT
maiden fable
#

Is it just me or the channel's activity has kinda died down as compared to before......?

slate swan
#

my boy the thing you're trying to make is useless

brittle ocean
#

how do I make a slash option that has all members of a server as the choices?

#

wait i think i found out....

fading marlin
#

type hint discord.Member to the param

brittle ocean
#

yeah i'm using nextcord

#

lol

#

also my code didn't work so the question is still relevant

fading marlin
brittle ocean
#

so like choices = nextcord.Member

fading marlin
#

type hint, not default

brittle ocean
#

wait type hint is???

#

sorry but i'm very bad with terms

fading marlin
#

arg: typehint = default

brittle ocean
#

o

brittle ocean
#

i am really being stupid now

fading marlin
#

it's not choices: nextcord.Member
it is

#

are you syncing?

grizzled reef
#

Imma make a casino bot

hazy prawn
#

How do I correct this..

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

Hey!

I am making a discord bot and was wondering if it is possible to make like a limit to how many people can click a button

Say if 5 people click a button, after the 5th person clicks the button the button turns disabled?

Thank you!

hazy prawn
#

Thank you

sick birch
slate swan
hazy prawn
#

It's always another problem after another

#

(this is line 43 on the bottom)

#

I really don't know what this means

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
sick birch
#

This should have all you need

sick birch
cloud dawn
hazy prawn
cloud dawn
sick birch
#

But a lot of tutorials will call a "bot" a "client" (which is incorrect)

cloud dawn
sick birch
#

This may have gotten you confused

hazy prawn
#

This is where it starts (cant figure out how to set it as an actual copyable thing, sorry)

cloud dawn
#

Just remove the lines with red underline.

sick birch
#

Also FYI having 2 @bot.event means that the 2nd one will override the first one

#

So worth keeping in mind

cloud dawn
#

Also if you want multiple on_message event you need listeners.

#

*in one file

hazy prawn
#

I'm not quite sure what a listener is (I have barely scratched the surface of how to code within python so bear with me on this)

cloud dawn
#

I highly recommend checking out the basics first, we're just doing it for you at this point.

sick birch
brittle ocean
fading marlin
#

have ya synced?

sick birch
brittle ocean
#

i think so

#

i have yes

hazy prawn
#

I am 1 error away from re-coding this bot entirely..

brittle ocean
slate swan
#

when i click the button it does what its supposed to i still get interaction error?

near wolf
#

how can you detect if a discord websocket connection is closed and the close code?

slate swan
unkempt canyonBOT
#

discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_connect "discord.on_connect") call.
slate swan
near wolf
sick birch
near wolf
slate swan
sick birch
near wolf
near wolf
slate swan
sick birch
slate swan
#

await interaction.response.defer(interaction.channel.send)?

#

or it is literally just await interaction.response.defer() interaction.channel.send

brittle ocean
#

how in the.....
Okay hear me out here. I want a SlashOption in a slash command that has all the members of the server as the options to choose from. How would i do that?

slate swan
cloud dawn
#

typehint the option.

cloud dawn
sick birch
# slate swan ?

In it's own line

await interaction.response.defer()
await interaction.channel.send("Hello, world!")
brittle ocean
#

no nvm i know what u mean, just not how to do it

cloud dawn
slate swan
slate swan
cloud dawn
sick birch
#

the french are very confused

slate swan
cloud dawn
slate swan
#

no, fr means for real

brittle ocean
#

lol

cloud dawn
cloud dawn
slate swan
#

frfr

cloud dawn
#

I mean french

brittle ocean
#

NL?

brittle ocean
#

nederlands heb ik ook geen moeite mee

#

anyhoo

brittle ocean
cloud dawn
#

Please speak English otherwise Robin gets upset.

brittle ocean
#

Sorry robin :3

cloud dawn
brittle ocean
#

i am so sorry

#

here:

@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
    interaction: Interaction,
    member: Member
    user:= SlashOption(
        choices=member,
        required=True,
        description="The user to remove the infractions from",
    ),
    remove=SlashOption(
        required=True,
        choices=str(clrinfr),
        description='put in "all" or 1-10 or a power of 5',
    ),
):
    if remove == "all":
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount="all"
        )
        embedr = nextcord.Embed(
            color=nextcord.Color.blurple(),
            title="Alle overtredingen van {interaction.user} zijn verwijderd!",
            description="Tip: je aan de regels houden werkt echt!",
        )
        await interaction.response.send_message(embed=embedr)
    elif remove == 0:
        return ValueError
    elif remove == int > 0:
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount=remove
        )
#

ignore choices=member for now

cloud dawn
#

py-cord it is

brittle ocean
#

heheh

cloud dawn
#

Is it py-cord?

brittle ocean
#

nextcord

#

ye

slate swan
#
def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 86400}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2
    return val * time_dict[unit]

@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time=None, *, reason=None):
    time=convert(time)
    if member == None:
        await ctx.send("Please mention a member.")
        return
    if time == None:
        await ctx.send("Please write the time!")
        return

    if member == ctx.author:
        embed = nextcord.Embed(
            color=nextcord.Colour.red(),
            description="You can't mute yourself !"
        )
        await ctx.send(embed=embed)
        return

    muterole = nextcord.utils.get(ctx.guild.roles, name="Muted")
    if muterole is None:
        muterole = await ctx.guild.create_role(name="Muted")

        for channel in ctx.guild.text_channels:
            await channel.set_permissions(muterole, overwrite=nextcord.PermissionOverwrite(send_messages=False))

    if muterole in member.roles:
        embed = nextcord.Embed(
            color=nextcord.Colour.red(),
            title="Mute Error :x:",
            description=f'This member is already muted!'
        )
        await ctx.send(embed=embed)
        return

    await member.add_roles(muterole)
    
    embed = nextcord.Embed(
            color=nextcord.Colour.green(),
            title=' Muted',
            description=f'**{member.mention}** is now muted reason: **{reason}**.'
        )
    embed.set_footer(text=f'Muted by {ctx.author}.')
    await ctx.send(embed=embed)
    await member.remove_roles(time=time)```

```nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: remove_roles() got an unexpected keyword argument 'time'
cloud dawn
brittle ocean
#

oh wow, i really am being stupid

#

sorry for the inconvenience

cloud dawn
#

I recommend using the docs and searching keyword.

cloud dawn
brittle ocean
cloud dawn
#

Might also be making a starter tutorial for the 4 most popular packages, including resources like this 👀

brittle ocean
#

It returns this error, i have no clue,

@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
    interaction: Interaction,
    user: nextcord.Member = SlashOption(
        name="user",
        required=True,
        description="The user to remove the infractions from",
    ),
    remove=SlashOption(
        required=True,
        choices=str(clrinfr),
        description='put in "all" or 1-10 or a power of 5',
    ),
):
    if remove == "all":
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount="all"
        )
        embedr = nextcord.Embed(
            color=nextcord.Color.blurple(),
            title="Alle overtredingen van {interaction.user} zijn verwijderd!",
            description="Tip: je aan de regels houden werkt echt!",
        )
        await interaction.response.send_message(embed=embedr)
    elif remove == 0:
        return ValueError
    elif remove == int > 0:
        database_functions.infractions(
            user_id=user, type="removeW", infrac=all, removeamount=remove
        )
cloud dawn
slate swan
#

help```ansi
ERROR: Failed building wheel for yarl

cloud dawn
brittle ocean
slate swan
#

im importing discord

#

with pip

slate swan
cloud dawn
brittle ocean
#

are u sure?

cloud dawn
slate swan
#

ok

#

reinstall pywin32 again 😝 🔫

unkempt canyonBOT
#

Hey @brittle ocean!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

brittle ocean
#

god

cloud dawn
#

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

brittle ocean
#

@cloud dawn

#

sorry if the pings annoy u btw, please tell if they do

cloud dawn
brittle ocean
#

as in the str()

cloud dawn
#

Oh no its good

#

Show me the on_guild_available there is the error.

brittle ocean
#

erhm

#

like in client.py?

cloud dawn
#

Or do you have like an embed somewhere.

brittle ocean
#

ehm yeah

cloud dawn
brittle ocean
#

well i really don't know

cloud dawn
#

Try that.

brittle ocean
#

sure

unkempt canyonBOT
#

examples/application_commands/choices.py line 16

choices={"one": 1, "two": 2, "three": 3},```
slate swan
#

choices are meant to be name-value pairs

brittle ocean
#

thats weird, it worked with a list of strings too tho

slate swan
#

thats a sequence iterable, unlike a string

brittle ocean
#

ah

#
clrinfr = [ "all",1,2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50,75,100,150, ]
#

oh god that formatting is horrid

#

well the idea was that you could choose to remove all infractions or a specific number, so a list of integers and one string

#

and put that as the choices for the slash option

slate swan
#

the attachment is smol

#

also you could send both embeds in same message lol

#

Maybe adding it as an image instead of a thumbnail will increase the size? But the dimensions of the actual image file probably also play a part...

#

Np

dull terrace
#

is there a way to emulate discord so i can work on a bot offline 7739monkathink

slate swan
#

... how does that matter? you can order the first embed first and the second one later
you can send 2 embeds in one message

slate swan
primal token
#

you can probably use a generator or asyncio events

potent spear
near wolf
#

i know i should ask it in discord api but no one is there so:
how can you detect if a discord websocket connection is closed and the close code?

static oak
#

does python keep a python bible or something?? something that explains the actual workings of the language???

slate swan
#

so its' the job of your library to handle that

near wolf
#

i use aiohttp

static oak
slate swan
# near wolf i use aiohttp

where exactly do you want to you check if the connection closed, like during connect or after the connection?

slate swan
near wolf
#

i tried to find aiohttp docs but i cant find anything about it

static oak
slate swan
#

anyone see the error here?

slate swan
slate swan
near wolf
slate swan
near wolf
#

oh how can i do that

slate swan
#
    async def listen_gateway(self) -> None:
       # _LOGGER.debug("Starting listening to gateway.")
        async for message in self.socket:
            #if self.is_connected is False:
                #self.is_connected = True
                #self._client.event_handler.dispatch("GATEWAY_CONNECTED", self._client)
            if message.type == aiohttp.WSMsgType.TEXT:
                await self._parse_payload_response(json.loads(message.data))
            elif message.type == aiohttp.WSMsgType.ERROR:
                "error from the gateway!"```
this is what i implemented in my library, `self.socket` there was the Websocket Response returned by `.ws_connect`
#

ignore the commented out part

near wolf
#

oh

#

await self.ws.receive_json() is what i use to receive thing

near wolf
slate swan
#

that works, but just for once, and yes you should be updating to this to keep listening to events regularly

near wolf
#

oh i have a function like this

#
    async def _receiveevent(self):
        while True:
            event = await self.ws.receive_json()
            self.lasts = event['s']
            if self.lasts == 11:
                _log.debug('received heartbeat ACK')
            if self.lasts == 1:
                await self._immediate()
            if self.lasts == 0:
                await self._ready(event)
slate swan
#

i use enums for them, makes life easier ```py
async def _parse_payload_response(self, payload: typing.Dict[str, typing.Any]) -> None:
op, t, d = payload["op"], payload["t"], payload["d"]
if op == WSEventEnums.HEARTBEAT_ACK:
self._latency = time.perf_counter() - self.keep_alive.last_heartbeat
return

    if op == WSEventEnums.HELLO:
        await self._hello_res(d)

    elif op == WSEventEnums.DISPATCH:
        self.keep_alive.sequence += 1
        await self._dispatch_events(payload)
near wolf
#

what is WSEventEnums?

slate swan
marsh sluice
slate swan
#

you shouldn't be using replit for discord bots

marsh sluice
#

Why?

slate swan
primal token
#

You can develop them but you shouldnt host them

marsh sluice
#

Ok

marsh sluice
slate swan
#

ofcourse

marsh sluice
#

Can you help me make one?

slate swan
#

well, ask your problems here shrug

marsh sluice
#

1.Idk how to make one

#

2.idk it will work

slate swan
#

what;s your experience with python?

marsh sluice
marsh sluice
#

I just know fors ifs whiles

#

Lists

#

Import things

slate swan
#
  • Python data types
  • Object Oriented Programming, difference between class and class instances, etc.
  • asyncio and async/await syntax
  • Loops and iterators
  • in, and, or, continue, break, return statements
  • Flow control ( if/else/elif , match/case )

this is a short list of things you should be aware about

marsh sluice
#

2,3 idk about

#

Data types int float boelan string list

#

It im right

slate swan
#

3 is avoidable when you start, you'll learn about you while you use the library
but 2 is a must.

slate swan
marsh sluice
#

I never used class @slate swan

thin raft
#

How can I react with :one: to a message

#

I can't get the unicode emoji

#

\1️⃣

fading marlin
#

U+0031

thin raft
fading marlin
#

yup

thin raft
#

kk ty

near wolf
rigid hare
#

is there a way to register commands programmatically? like, i have some commands >pat, >hug, >kiss, etc that do very simmilar things, im looking to try and build the commands by looping over a dictionary, and register them that way, is it possible?

fading marlin
#

sure, though I don't think it's any better than just manually doing those. You basically want to create a coroutine without the command decorator, and instantiate a Command class with all the args you would usually pass to the command decorator, and you use the coroutine as your callback. Then you just add_command

async def callback(ctx: commands.Context, ...) -> Any:
    ...


command = Command(callback, name="...", aliases=["...", "..."], ...)
bot.add_command(command)
#

another alternative is to make a "parent" command and use aliases in conjunction with Context.invoked_with, but that might not look very good if you've got a help command

fossil quartz
rigid hare
#

and itll make it easier to add new ones

#

they basically all call one function, so i can just use partials to generate it from strings in a dictionary

#

its like this py @commands.command(name='pat') async def pat(ctx, target, *extra): await do_reaction(ctx, target=target, folder="pat", message="&u pat &t") so i can just use a dict as args for do_reaction

fossil quartz
#

I stopped coding for 1 year and a half and might need to read the whole python documents again 🙄 you guys already know the out put of this, it sends a message then edits it, sends another message then edits it since im running message.edit and ofc thats what its supposed to do, but what im trying to so is keep editing the same message

async def test(ctx):
    count = 0
    while True:
        #print(count)
        message = await ctx.send(count)
        count += 1
        await asyncio.sleep(1)
        await message.edit(content=count)```
sick birch
fossil quartz
#

Tt

#

Ty*

sick birch
#

Though it seems like this is just a countdown type timer?

#

I think it might be better to use something like <t:1669340096:R>

fossil quartz
#

But its gonna be a struggle cause what if 3 ppl do the command in diff channels of the server or some

sick birch
#

5 message edits/sends per 5 seconds

fossil quartz
fossil quartz
#

Oof

sick birch
#

Trying to do something that updates frequently in discord is not a good idea

fossil quartz
#

Shit so hard

fossil quartz
#

Can never code my ideas

lethal bloom
#

I am trying to get him to choose a name from a list and place it as in the photo but it comes out as what is in the second photo

fasoto = open("namesrandom.txt", "r")
archivononame = open('nameselecti.json','w')
archivononame.write("")
archivononame.close()
pediatra = fasoto.readlines()
pediatrato = f'{random.choice(pediatra)}"'
username = '"username"'
aline = f'"{pediatrato}'

with open("nameselecti.json", "a") as pediatro:
    pediatro.write('{'  +  "\n"  +  f"    {username}:{aline}"  +  '}')
short pulsar
#

joke, i saw the other code lol

slate swan
slate swan
#

Just put this

#

For default emojis bot doesn't need unicodes to use

#

But for custom emoji they need this sequence: <:name:id>
like
!python
This thing is for this custom emoji: python

shrewd apex
#

damn i didn't know that

vale wing
#

Discord stoopid why couldn't they do like <e:123456789012345678> syntax, the heck for is separating animated emojis and even using their names

#

Also do they still not let you copy emoji ID like a normal ID

shrewd apex
#

get the id from there

vale wing
#

On desktop you can copy link but that's not what I call normal way

#

Normal way would be "copy ID" button

shrewd apex
#

¯_(ツ)_/¯

vale wing
#

I am gonna complain to their support about this

shrewd apex
vale wing
#

💪🤗💪
🦵 🦵

slate swan
#

Ooo, thanks. Learnt something new

vale wing
#

Button better

shrewd apex
slate swan
shrewd apex
slate swan
#

Oh, forgot. my bad :[

coral mirage
#

you awake?

slate swan
#
@bot.event
async def on_message(message):
    embeds = message.embeds
    for embed in embeds:
        print(embed.to_dict())

So I have this code, but for testing purposes I want to make it so I can just pick a specific embed to turn into the dict. How do I do that?

near wolf
#

what are snowflake ids?

slate swan
naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

buh
naive briar
#

🤷

slate swan
slate swan
slate swan
slate swan
#

Like today is nov 25, 2022 = so many seconds

#

<t:126377373:R>

near wolf
slate swan
#

Unfortunately I don't have much information about snowflake id's tho :[[

near wolf
#

i wanna know how can you get the ids you receive in a gateway event

slate swan
#

O.o

#
@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: str):
  username = a.guild.get_member(user)
  await a.guild.unban(username)
  await a.response.send_message(f"Unbanned {username}")
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unbanid' raised an exception
slate swan
#
Traceback (most recent call last):
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 51, in unbanid
    await a.guild.unban(username)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/guild.py", line 3481, in unban
    await self._state.http.unban(user.id, self.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'unbanid' raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
heavy folio
#

yeah username is none

slate swan
#

Yeo none

#

Use bot.get_member

heavy folio
#

you'd be better off typing user to be a discord.User and handle UserNotFound in an error handler

heavy folio
slate swan
heavy folio
slate swan
#

But member too exist as far i know

slate swan
#

So ofc the member will be not in the server

heavy folio
#

well he cant unban a member, he can only unban users

slate swan
#

Need to use bot.get_user method

#

can I get a member in the bans?

heavy folio
slate swan
slate swan
heavy folio
slate swan
#

Well imma show quick example:

@miner.tree.command(name='unbanid', description='unbans an id from a server, bot must be in it')
@app_commands.describe(user = 'Put a userid!')
async def unbanid(a: discord.Interaction, user: int):
  username = bot.get_user(user)
  await a.guild.unban(username)
  await a.response.send_message(f"Unbanned {username}")
#

Here i just edited your code

upbeat otter
slate swan
upbeat otter
upbeat otter
slate swan
#

I am showing the interaction.send and interaction.edit method

#

!d nextcord.Interaction.send

#

Here @upbeat otter

upbeat otter
#

it doesn't have a slash context, so why'd anyone use ctx

#

that looks equally bad

slate swan
#

So i just showed example 💀

upbeat otter
#

I don't even remember the convo so anyways

slate swan
#

;-;

slate swan
near wolf
#
Traceback (most recent call last):
  File "F:\fun\Desktop\coding practice\python practice\test.py", line 7, in <module>
    client.run()
  File "F:\fun\Desktop\coding practice\python practice\x\client.py", line 17, in run
    asyncio.run(self._http.run())
                ^^^^^^^^^^^^^^^^
  File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 33, in run
    asyncio.run(self.init())
  File "C:\Program Files\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 41, in init
    await self._connect()
  File "F:\fun\Desktop\coding practice\python practice\x\httpc.py", line 45, in _connect
    async with self.cs.ws_connect(self.url) as ws:
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 1141, in __aenter__
    self._resp = await self._coro
                 ^^^^^^^^^^^^^^^^
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 779, in _ws_connect
    resp = await self.request(
           ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\aiohttp\client.py", line 400, in _request
    raise RuntimeError("Session is closed")
RuntimeError: Session is closed``` httpc.py:https://paste.pythondiscord.com/aporoqanej client.py:https://paste.pythondiscord.com/uhogoloped
near wolf
#

i shown

slate swan
#

Ohk

naive briar
near wolf
#

oh

#

but what can i do

#

i dont want it to close

high tapir
#

how can i write discord mirror channel bot? Firstly i need to connect to websocket right?

and have open browser with already logged in account and have opened channel which i want to mirror right?

naive briar
# near wolf but what can i do

You can simply use session.get without using the session as a context manager, but you could get a warning about unclosed session after the program ends. Like:

async with self.cs.get(...) as resp:
    ...

Another way that you can ensure that the session will be closed after the program ends is to make a start or main function where you can make the session a context manager and just pass the session in the class constructor. Like:

async def main():
    async with aiohttp.ClientSession as cs:
        client = Client(session=cs, ...)
near wolf
#

ive got another problem

#

now nothing happened and it didnt seems like successfully connected to websocket

#

nvm its working

brittle ocean
#
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1.choices.0.value: Could not interpret "1" as string.
In options.1.choices.1.value: Could not interpret "2" as string.
In options.1.choices.2.value: Could not interpret "3" as string.
In options.1.choices.3.value: Could not interpret "4" as string.
In options.1.choices.4.value: Could not interpret "5" as string.

How is this happening?

@bot.slash_command(guild_ids=GUILD_IDS)
async def clearinfracs(
    interaction: Interaction,
    user: nextcord.Member = SlashOption(
        required=True,
        description="The user to remove the infractions from",
    ),
    remove=SlashOption(
        choices=[1, 2, 3, 4, 5],
        required=True,
        description="put in 00 to remove all or 1-10 or a power of 5",
    ),
):
upbeat otter
naive briar
#

All choices must be a string

slate swan
#

I didn't know about that

#

Thanks ;-;

brittle ocean
slate swan
#

Ofc

brittle ocean
#

didn't know that

#

explain this then

#

(parameter) choices: Dict[str, str | int | float] | Iterable[str | int | float] | None

slate swan
#

choices can def be an int lol

brittle ocean
#

yeah i though as much, why else would it give that option

#

but why is it giving the error then?

slate swan
upbeat otter
slate swan
# brittle ocean but why is it giving the error then?

no clue here is an example tho

@bot.slash_command(guild_ids=[TESTING_GUILD_ID])
async def choose_a_number(
    interaction: nextcord.Interaction,
    number: int = SlashOption(
        name="picker",
        choices={"one": 1, "two": 2, "three": 3},
    ),
):
    """Repeats your number that you choose from a list

    Parameters
    ----------
    interaction: Interaction
        The interaction object
    number: int
        The chosen number.
    """
    await interaction.response.send_message(f"You chose {number}!")
#

how does on mention work

alpine cove
slate swan
#

sned

#

was literally ab to link lol

#

send

#

just go to dpy docs

alpine cove
slate swan
#

and search on_mention

alpine cove
slate swan
slate swan
slate swan
#

It's for the prefix only tho 💀

#

If you want the bot to show a message when mentioned you need to use event

#

can someone give me a quick example

#

@slate swan i am using on message

#

Wait please

high tapir
#

how to let my bot send message to channel with specific id

slate swan
slate swan
primal token
slate swan
#

da

slate swan
slate swan
primal token
#

sometimes its just caching issues lol

slate swan
#

Oh yeah, question of my own...

slate swan
#

When I do something along the lines of:

channel = self.bot.get_channel(941380693164949574)
print(channel)

It prints only the channel name and nothing else. Is this normal? Just curious.

naive briar
slate swan
#

it should print channel objects

#

Exactly

#

like name, id

slate swan
#

Yup just did and it works as expected

#

!eval

channel = bot.get_channel(343944376055103488)
print(channel)
#

oh forgot 💀

#

I can even send stuff into that channel

slate swan
hushed galleon
slate swan
#

cool

#

I see, thanks

#

can i send an attachment using its proxy_url ?

slate swan
slate swan
near wolf
abstract onyx
#

anyone got good tutorial video for discord bot? (updated if possible)

slate swan
#

or glowstik

#

search them in yt

abstract onyx
abstract onyx
abstract onyx
slate swan
#

;]

abstract onyx
#
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = "d!")

@client.event
async def on_ready():
    print("Bot is ready")
client.run("")```
#

I get this error

naive briar
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

abstract onyx
naive briar
#

Maybe maybe maybe

wintry shoal
wintry shoal
naive briar
#

What?

abstract onyx
naive briar
#

You'll clearly see that it is literally telling you how

slate swan
#
import discord

intents=discord.Intents.all()
bot = commands.Bot(......, intetns=intents)
#for this method you have to enable all intents in your app!
slate swan
wintry shoal
#

whatever u need

naive briar
slate swan
naive briar
#

Wait

slate swan
naive briar
#

I'm an idiot

abstract onyx
#

@slate swan do you have updated tutorial because the channel you said me to watch are outdated

slate swan
#

Oh Civo

#

I forgot about that guy

#

He has updated things

abstract onyx
#

alright thank you

slate swan
#

Yes for sure

#

If you don't find correct channel
Search civo discord.py

slate swan
#

!d intents

slate swan
slate swan
#

Looks fine

high tapir
#

i mean that i want to pass an argument somehow

#

i mean like that

#

but i cant do it in that way

slate swan
#

Also what param u want to send

high tapir
dense merlin
#

anyone know how to add slash commands?

slate swan
#

Forgot uf

high tapir
#

and images

slate swan
dense merlin
slate swan
high tapir
#

im just writing script and im on the last step

slate swan
dense merlin
#

ok

high tapir
#

and need just to send this what i received from earlier function

#

but i dont know how i can pass it

slate swan
#

Ahhhhh

high tapir
slate swan
#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
slate swan
#

Thanks bruh

slate swan
#

I mean the params xd

high tapir
#

i hate this discord things... xd

dense merlin
#

teach me slash commamds

alpine cove
dense merlin
#

dont understand

slate swan
#

If you are using discord.py. Here is an example:

@bot.tree.command(name="slash-command-name", description="Command description")
async def slash(interaction: discord.Interaction):
  await interaction.response.send_message("Hello! You used a slash command.")
#

Here take 💀

slate swan
dense merlin
#

What importa do

high tapir
#

i mean i cant use await i think

#

because its not in async function

slate swan
slate swan
high tapir
sick birch
high tapir
#

lel hows that possible? and hello robin

#

just copied this

slate swan
sick birch
#

Does the bot have access to that channel?

#

Also it looks like you're using asyncio.run() to call it - so it's not out of the question that the bot's cache isn't populated just yet

high tapir
#
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
async def szef(param):
    channel = client.get_channel(1014245637245653125)
    await channel.send(param)
asyncio.run(szef('Hello im SSR'))
high tapir
#

ugm sorry i have it written like that

#
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
async def szef(param):
    channel = client.get_channel(1014245637245653125)
    await channel.send(param)
asyncio.run(szef('Hello im SSR'))

client.run('t0ken')
cloud dawn
#

Almost

high tapir
#

ok i change it

#

to this

#
intents = discord.Intents(messages=True, guilds=True, message_content = True)
client = discord.Client(intents=intents, case_insensitive=True)
client.run('t0ken')
async def szef(param):
    channel = client.get_channel(1014245637245653125)
    await channel.send(param)
asyncio.run(szef('Hello im SSR'))
#

it looks like it works but bot doesnt send message

slate swan
slate swan
#

I think it should be
def szef(param):

high tapir
#

guys in discord py told me to did so

#

without async at all?

slate swan
#

Yep

high tapir
#

RuntimeWarning: coroutine 'szef' was never awaited
szef('Hello im SSR')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
#

Do
await asyncio.run()

cloud dawn
# high tapir ```py intents = discord.Intents(messages=True, guilds=True, message_content = Tr...
import asyncio
from discord import Client, Intents

intents = Intents.default()

client = Client(intents=Intents)

@client.event
async def on_ready() -> None:
    # Example code, do not use in practise
    channel = client.get_channel(1014245637245653125)
    await channel.send("cheese")

async def main() -> None:
    async with client:
        await client.start("token")

if __name__ == "__main__":
    asyncio.run(main())

cloud dawn
slate swan
#

I am not familiar with asyncio

#

Xd

faint mural
#

Is it possible to stop links from embedding with either web-hook or normal message?
Can't find anything on the docs

faint mural
#

LorbWheartgirlOwO thanks

coral mirage
#

hey @slate swan, you around?

slate swan
high tapir
#

thanks it worked ❤️

coral mirage
#

alright, enjoy your food. Tag me when your done.

slate swan
#

Kk

high tapir
#

i was struggling with this for a bit thanks brother @cloud dawn

cloud dawn
#

Magic fingers 🐒 😏

high tapir
#

indeed haha

cloud dawn
high tapir
cloud dawn
#

Or do you want to change it trough a command?

high tapir
#

no i dont want to do that in that way

#

i need to pass argument from earlier function

#

like previous one

sick birch
cloud dawn
#

Okay a bit more difficult but I'll get it as close as possible.

sick birch
#

Right because we can't do it in setup_hook (cache is not populated)

sick birch
#

@high tapir you could do:

class CustomBot(commands.Bot):
  def __init__(self, *args, **kwargs) -> None:
    super().__init__(*args, **kwargs)
  async def setup_hook(self) -> None:
    channel = await self.fetch_channel(123456789)
    await channel.send("Some message")

bot = CustomBot(command_prefix="!", intents=discord.Intents.default())
bot.run()
#

But that goes back to the issue of custom text

neat sequoia
#

hello

cloud dawn
# high tapir yup i need custom text
import asyncio
from discord import Client, Intents

intents = Intents.default()


class AmazingClient(Client):
    def __init__(self, msg: str) -> None:
        self.msg = msg
        super().__init__(intents=intents)

    async def on_ready(self) -> None:
        # Example code, do not use in practise
        channel = client.get_channel(1014245637245653125)
        await channel.send(self.msg)


async def main(msg: str) -> None:
    async with client:
        await AmazingClient(msg).start("token")

if __name__ == "__main__":
    asyncio.run(main("cheese"))

high tapir
#

or here i pass the argument

#

i mean where i can put my string that i want to print

cloud dawn
high tapir
#

yeah basically

sick birch
high tapir
#

im doing websocket

#

on another account

cloud dawn
high tapir
#

from channel and i want to send some of this messages

#

and this is my "custom string" that i want to send

slate swan
#

might work mb

cloud dawn
#

He does fetch it so..

sick birch
#

I would probably extract it into a seperate function: @high tapir


async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
    return await channel.send(message)

class CustomBot(commands.Bot):
  async def setup_hook(self) -> None:
    channel = await self.getch_channel(123456) # this will fetch from API
    await send_message("This is set on setup_hook!", channel=channel)

  async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
    if channel := self.get_channel(channel_id):
      return channel
    else:
      return await self.fetch_channel(channel_id)

bot = CustomBot(...)

@bot.command()
async def some_command(ctx: commands.Context, ...) -> None:
  channel = await self.getch_channel(123456) # this will get from cache
  await send_message("This was sent in a command, later on", channel=channel)
#

This way you have an extracted function you can call whenever

#

Just a proof of concept I came up on the spot, lol. Not guaranteed to work

sick birch
# slate swan might work mb

I've sent messages using my bot with just the REST API without a websocket connection. It should work just fine

#

if the discord.py rest client was designed well, it would allow you to do this without any dependence on the websocket

slate swan
#

i think the rest is, but the session is not, either one of these

sick birch
#

Worth a shot. In my head, if I can send a message via rest api without a socket connection, discord.py should be able to let you as well. But I haven't tested it with discord.py so not sure

#

Well the setup_hook gets called after start/run has been called, yes?

cloud dawn
#
    async def login(self, token: str) -> None:
        _log.info('logging in using static token')

        if self.loop is _loop:
            await self._async_setup_hook()

        if not isinstance(token, str):
            raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
        token = token.strip()

        data = await self.http.static_login(token)
        self._connection.user = ClientUser(state=self._connection, data=data)
        self._application = await self.application_info()
        if self._connection.application_id is None:
            self._connection.application_id = self._application.id

        if not self._connection.application_flags:
            self._connection.application_flags = self._application.flags

        await self.setup_hook()
#

Setup hook is the last thing in the login so it will most likely work.

high tapir
#

dont know whats going on here there 👍

sick birch
#

we should be ok then

slate swan
#

that should work then

sick birch
#

Looks like Danny had the foresight to design it that way

cloud dawn
slate swan
#

@coral mirage now tell

viral dock
#

Hello I have a question. On my chromebook intents.message_contents = True works but on my windows pc I get the error: AttributeError: 'Intents' object has no attribute 'message_content'
Can someone help me with this?

viral dock
#

ohw

sick birch
slate swan
#

hm you can just ```py
client = Client(...)
client.event(lambda setup_hook *_: client.http.send_message("your text"))

#

Same answer on same time cool

high tapir
viral dock
#

in terminal

coral mirage
# slate swan <@658006319361556521> now tell

So, I want to invoke a command inside another command. Idk if you familiar with select and buttons, but I'm trying to select a command. I try what you told me and I actually have an idea, but I'm still missing something.

#

idk if its invoke

slate swan
#

You can't really invoke a command but just copy paste the code of that command and put it on dropdown call back

sick birch
slate swan
#

Idk better idea, but i use this

coral mirage
#

can you send an example?

primal token
coral mirage
sick birch
slate swan
#

Oh u were telling me ;-;

coral mirage
#

do you guys get pay to help out?

slate swan
#

Nah

#

We guys just do for free 💀

#

Uk it's fun

sick birch
slate swan
slate swan
high tapir
# sick birch Yes

wtf it looks complicated what do i need to replace? to start setting my strings i dont understand this part this also

primal token
slate swan
#

sorry i misread it

coral mirage
slate swan
#

TypeError: Callback is already a command.

slate swan
# primal token huh

yeah thats possible as well, but that's what client.event will do internally anyways

#

umm

slate swan
#

what does that error mean?

slate swan
#

im' lazy to type =

primal token
#

Can relate

coral mirage
slate swan
high tapir
#
async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
    return await channel.send(message)

class CustomBot(commands.Bot):
  async def setup_hook(self) -> None:
    channel = await self.getch_channel(1014245637245653125) # this will fetch from API
    await send_message("This is set on setup_hook!", channel=channel)

  async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
    if channel := self.get_channel(channel_id):
      return channel
    else:
      return await self.fetch_channel(channel_id)

bot = CustomBot(...)

@bot.command()
async def some_command(ctx: commands.Context) -> None:
  channel = await self.getch_channel(1014245637245653125) # this will get from cache
  await send_message("This was sent in a command, later on", channel=channel)
primal token
#

It means the function object has already been registered as a command

high tapir
sick birch
#

note that channel needs to be a discord.Channel object and not a primitive datatype like a string for a channel name or an integer ID

slate swan
primal token
#

why is getch_channel so long? just do

async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
    return self.get_channel(channel_id) or await self.fetch_channel(channel_id)
high tapir
primal token
sick birch
high tapir
#

yeah i think this shit is too hard for me i dont understand this weird library at all i stopped on that, thanks for your help rob anyways


async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
    return await channel.send(message)

class CustomBot(commands.Bot):
  async def setup_hook(self) -> None:
    channel = await self.getch_channel(1014245637245653125) # this will fetch from API
    await send_message("This is set on setup_hook!", channel=channel)

  async def getch_channel(self, channel_id: int) -> Optional[discord.Channel]:
    if channel := self.get_channel(channel_id):
      return channel
    else:
      return await self.fetch_channel(channel_id)

bot = CustomBot('t0ken')

@bot.command()
async def some_command(ctx: commands.Context) -> None:
  channel = await self.getch_channel(1014245637245653125) # this will get from cache
  await send_message("This was sent in a command, later on", channel=channel)

send_message("YOUR TEXT HERE", channel=)

slate swan
high tapir
slate swan
#

what does not work

high tapir
#

async def send_message(message: str, *, channel: discord.Channel) -> discord.Message:
AttributeError: module 'discord' has no attribute 'Channel'. Did you mean: 'channel'?

slate swan
#
@bot.command
async def balance(ctx):
    user_id = ctx.author.id
    if find_member(user_id) == None:
        insert_user(ctx.author.id)
    user_info = find_member(ctx.author.id)
    embed=discord.Embed(title=f"{ctx.author.display_name}'s balance", description=f"You have {user_info['coins']}", color=0xFF5733)
    embed.set_author(name=ctx.author.display_name,icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)```
slate swan
#

when I type $balance it says no command foound

primal token
#

and you should use is in if find_member(user_id) == None:

sick birch
slate swan
sick birch
#

Too early for this shit sorry

primal token
#

!d is

unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

slate swan
#

but would it make any difference from == in this situation?

high tapir
# sick birch Too early for this shit sorry
async def send_message(message: str, *, channel: discord.TextChannel) -> discord.Message:
    return await channel.send(message)

class CustomBot(commands.Bot):
  async def setup_hook(self) -> None:
    channel = await self.getch_channel(1014245637245653125)

   await send_message("This is set on setup_hook!", channel=channel)

  async def getch_channel(self, channel_id: int) -> Optional[discord.TextChannel]:
    if channel := self.get_channel(channel_id):
      return channel
    else:
      return await self.fetch_channel(channel_id)

bot = CustomBot('t0ken', intents=intents)

@bot.command()
async def some_command(ctx: commands.Context) -> None:
  channel = await self.getch_channel(1014245637245653125)
  await send_message("This was sent in a command, later on", channel=channel)

send_message("YOUR TEXT HERE", channel=discord.TextChannel)

send_message("YOUR TEXT HERE", channel=discord.TextChannel)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback Last error i guess

sick birch
#

Make sure you actually define intents too

primal token
sick birch
#
intents = discord.Intents.default()
intents.message_content = True
bot = CustomBot("token", intents=intents)
primal token
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True False
high tapir
fleet iron
#

How would I make it so even after the bot restarts it saves the value of seomthing?

#

For example by default when I do "-welcome" it says Welcome to the server #user, but when I do -welcome (Welcome Message) it says the message I chose, and continues to after it restarts

#

@primal token @sick birch hel please

primal token
fleet iron
#

Like write it themselves

primal token
#

per guild i suppose?

fleet iron
#

yes

#

Actually, it's just 1 server so it doesnt matter

primal token
#

You can use JSON or if you're going to other guilds to avoid further trouble you can use sqlite with an async driver

stiff geyser
#

hey im currently working on an scraper bot, which scrapes site information with requests. Im using a discord bot for the commands so when i f.E am typing ' !scrape build' its replacing the {query} i defined in the link so its inserting the 'build' into the link. But im currently stuck and arent getting a response from the bot.

slate swan
#
@client.event
async def on_message(message):

    if (message.channel.id == 1003326813558280293):
            
        author = message.author
        image_url = message.attachments[0].url``` how to fix this error ?
primal token
#

it means the message didnt have attachments and no need for the brackets in the condition

high tapir
#

anyways will anyone know how to shut down log bot in then shut down ?

def szef_test(a): 
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents, case_insensitive=True)
    @client.event 
    async def on_ready():
        channel = client.get_channel(1014269272467456130)
        await channel.send(a)


    client.run('t0ken')
    client.close()
    return
#

RuntimeWarning: coroutine 'Client.close' was never awaited
client.close()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

primal token
#

close is a coroutine

#

and it would never run

slate swan
high tapir
primal token
slate swan
#

all intents are activated

primal token
#

Can you show your code and if the code is correct then you would need to check if the message has an attachment in the first place

slate swan
#
import requests
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix='!', intents=intents)

@client.event
async def on_message(message):

    if (message.channel.id == 1003326813558280293):
            
        author = message.author
        image_url = message.attachments[0].url

        req = requests.get(image_url, stream=True)
        if req.status_code == 200:
            embed = discord.Embed(
                title=f'Nouveau Succès de {author}',
                colour=discord.Colour.blue()
            )
                
            await message.channel.send(embed=embed)


client.run('token')```
#

@primal token

primal token
#

you're missing the message_content intent!

#

add intents.message_content = True under intents.members = True

slate swan
#

ok thanks, I'll try

primal token
#

also, you shouldnt be using requests

#

!pypi aiohttp | Use this!

unkempt canyonBOT
slate swan
primal token
#

🦦

slate swan
#

why aiohttp ? it's better than requests

primal token
#

Its async so it wont block the event loop!

#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

okay

#

how can I check if the message contains the image of a url ?

#

@primal token

naive briar
#

What

shrewd apex
#

image of a url hmm

#

not sure if its literally the question or said opposite since it seems valid either way

unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
Decorators (see !tags decorators)
Inheritance (overriding methods)
Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

west hare
#

(couldn't post media in general, so posting here)
when I click on that profile I was for a moment get scared and think that a "something" is related hidden part underneath discord thinkmon

#

Basically this popup didn't fit in height, so instead of relocating above it shift whole discord layout adding space underneath (dark area). The whole discord stays "lifted" in this state until I click view server.

coral mirage
#

can someone tell me what I'm missing please 😦

naive briar
split forge
#
    return await self._callback(interaction, **params)  # type: ignore
  File "/home/container/main", line 137, in crash
    if interaction.author.id != bot.user.id:
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'crash' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
naive briar
#

So, swap the select and interaction position in the callback argument

unkempt canyonBOT
split forge
#
  File "/home/container/main", line 138, in crash
    await interaction.response.send_message(embed=discord.Embed(description=f"Check your direct messages! {message.author.mention}",
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'crash' raised an exception: NameError: name 'message' is not defined
#

lmafo

split forge
naive briar
#

What

#

The error is saying exactly what the problem is

coral mirage
slate swan
#

is it possible to only view certain buttons at a specific embeds

fast lotus
#

can someone advise me free hosting for bot?

primal token
naive briar
#

What's the problem

#

Turn on message_content intent

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

naive briar
#

Turn it on in your code

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

marsh sluice
#

How to make a discord bot?

#

In python

naive briar
marsh sluice
dry kelp
#

@sick birch I've made that oauth2 request work

#

What's the ratelimit for that?

#

like adding members back to guild

primal token
#

guilds

#

Thats for python?

hushed galleon
#

those last two lines are (extremely) outdated code, dpy's renamed all server attributes to guild and changed Client.add_roles() to Member.add_roles()

naive briar
#

No, it's not

#

About the docs I mean

hushed galleon
#

!d discord.Member.add_roles < most up to date version of the documentation @slate swan

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
primal token
#

Python documentation is for python
Discord.py documentation is for discord.py a library of python

Why would Pythons docs feature discordpy's docs?

dry kelp
#

On the even on_member_ban How can i check how many members has been banned

naive briar
#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
primal token
dry kelp
#

Oh

#

Fuck so in case of a massban ratelimit would be crazy

#

I will unban just the people that allowed the OAuth2 hopefully avoiding the ratelimit

hushed galleon
#

an example usage: ```py

Get a role object (typically by role ID)

role = ctx.guild.get_role(1234)

Add it to the command author

await ctx.author.add_roles(role)```

wary crystal
#

If you can 100% confirm that the role will never not be there, you could safely skip the cache all together and use discord.Object(id=...)

naive briar
#

Big brain time

hushed galleon
#

ID as in the numeric identifier given to the role

#

if you have the developer mode enabled in your discord app, you can right click the role and copy the ID there

#

you didnt define the member variable in your function...

dry kelp
#

didn't see ctx.reply in a while 🥹

hushed galleon
#

the first parameter of that command, ctx, is the commands.Context object, and it contains a lot of helpful attributes for you to do things from your command

dry kelp
#

/ commands are just better

hushed galleon
#

for example, ctx.author gives you the user/member that invoked your command

flint isle
#

how do i send emojis in custom or custom animated emojis disnake again?

naive briar
#

The function is already a callback of an command

#

Send the code of the function

#

With its decorators

#

Or just the decorators

sick birch
#

Sorry bit busy with the help system migration atm

vocal magnet
#

?

#

Everyone is a volunteer here, so you are not entitled to get help at all times. Ask your question, and if someone can help they will.

near wolf
#

is there a way to turn the user flags(integer) back to 1 << something value?
or is there a way to calculate it?

vocal magnet
#

the moderation role it pingable to report people not following to rules, not to ask for hlep

dry kelp
#

Am i doing something wrong in this code?

#

Because it won't unban the user that has been banned on_member_ban and ofc it won't rejoin the guild

slate swan
unkempt canyonBOT
#

discord/flags.py lines 171 to 172

def _has_flag(self, o: int) -> bool:
    return (self.value & o) == o```
slate swan
#

this is how dpy handles it

#

there's already a command called pof, you can't have 2 of them

#

@bot.command(commands) ????

slate swan
dry kelp
#

Docker is weird. Prints won't be executed

primal token
#

what?

dry kelp
dry kelp
#
    @commands.Cog.listener()
    async def on_member_ban(self, guild, user):

        async for i in guild.audit_logs(
            limit=1,
            after=datetime.datetime.now() - datetime.timedelta(minutes=1),
            action=disnake.AuditLogAction.ban,
        ):

            print("before resp")
            oauth_response = await OAuth2User.get_or_none(discord_id=user.id)
            print("after")
            if oauth_response:
                print("unban")
                await guild.unban(
                    user, reason=f"{user.name} Has been added back via OAuth2"
                )
                logger.info(f"Unbanned {user}-{user.id} from {guild.name}-{guild.id}")
                logger.info(f"Re-adding member {user.id} to {guild.id}.")
                print("adding")
                await add_to_guild(oauth_response.token, user.id, guild.id)
                raise Exception("a")
#

@slate swan does this look wrong to u?

#

prints and exceptions won't raise for some weird reasons.. docker its just fucked up

dry kelp
#

print(...)

orchid salmon
#

hey. i haven't made a discord bot since the original library stopped maintenance. where's the current one that everyone is using?

orchid salmon
#

oh great

slate swan
lilac steeple
#

.run print("hello")

#

.bot

#

how do i run code

#

i forgot

#

{}

#

.run

#

.run
print("hello")

sick birch
unkempt canyonBOT
#

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

hello
sick birch
#

But you should use #bot-commands for it

lilac steeple
#

oh

#

i thought the was the place sorry

#

thx tho

sick birch
#

no worries

dry kelp
#

still weird no errors

#

like obj not found

pliant gulch
#

With docker you either need to run python via -u or manually set python unbuffered to 1

#

Also docker logs CONTAINER

bright wedge
#

role.mention

#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
bright wedge
#

like:

role = get_role()
role.mention
#

or you can do <@&role.id>

#

some me what you have done

#

send me the whole code

#

oh, you give some "properties" in role?

#

use the role ids

hollow quarry
#

you can repost that vd, just replace the invite link with <invite link> or something

bright wedge
#

send me one of your roles id

#

this is role id 1045875292406808576 ?

#
embed.add_field(name="1 boost ->", value="<@&1045875292406808576> + pic perms", inline=False)
#

try this

#
mentions:
<@&id> roles
<@id> member
<#id> channel
#

use it as rule!

primal token
slate swan
sick birch
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
slate swan
slate swan
#

what does this mean

slate swan
slate swan
#

ohk

slate swan
#

then wait for their answer ig

slate swan
slate swan
#

Hello!

I am making a discord bot and I want to track how many people click the button

So like

Say 1 user clicks the button it edits the embed to there mention

And then another user clicks the button it adds another mention to the embed

How would I do somethig like that?

slate swan
# vocal snow What have you done so far?
            async def join_callback(self, inter:discord.Interaction):
                joiner = inter.user
                number = 0
                if number == 1:
                    await inter.response.send_message(f"**Unfortunatly this lobby is closed.**")
                else:
                    number += 1
                    join.disabled = True
                    join.label = str("Join Match 1 (Not Joinable")
                    await inter.message.edit(view=self)
#

But for like when 2 peopel can join I want it to display those 2 people

vocal snow
#
number = 0
if number == 1:
``` ![pithink](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "pithink")
#

That if statement is never going to run

slate swan
slate swan
bright wedge
vocal snow
slate swan
slate swan
bright wedge
#

are you kidding us?

vocal snow