#discord-bots

1 messages ยท Page 277 of 1

hasty pike
#

rip @shrewd apex

warm coral
#

vscode terminal?

slate swan
#

Bro Asher take water

shrewd apex
#

files rest within folders not within files ๐Ÿ—ฟ

slate swan
cloud dawn
shrewd apex
cloud dawn
#

Isn't a zip file technically just one file?

slate swan
#

Pandab

shrewd apex
#

u cant make edits

cloud dawn
#

niti

slate swan
#

Bro anyone solve my problem

shrewd apex
#

with unzipping it

cloud dawn
shrewd apex
#

totally

slate swan
cloud dawn
warm coral
#

@shrewd apex i typed it in the terminal and i doesnt work too

#

the vscode terminal

slate swan
shrewd apex
warm coral
#

ooooh

#

ok

cloud dawn
slate swan
shrewd apex
#

exactly

warm coral
#

im so dumb

slate swan
slate swan
shrewd apex
#

i am gonna go sleep gn guys

cloud dawn
cloud dawn
slate swan
#

Yes

buoyant quail
slate swan
#

Lol

cloud dawn
#

Or both sides? Uknown amount of spaces?

slate swan
#

Yes bro both side

hasty pike
#

What are you guys even doing

cloud dawn
#

a single space on both size or uknown amount?

slate swan
#

See

#

\x

hasty pike
#

@buoyant quail how do I update button emoji on after interaction?

cloud dawn
slate swan
hasty pike
cloud dawn
#

Could you show the code of a sentince that has that weird overlapping?

buoyant quail
#

I believe you can just do button.emoji = ...

And then you need to edit the message ofc

slate swan
#

def slugify(value: str, allow_unicode: bool = False) -> str:
"""
slugify the names of files

:param value: string to be slugify
:type value: str
:param allow_unicode: allow unicode
:type allow_unicode: bool
:return: string after slugify
:rtype: str
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')

hasty pike
#
    if player.is_playing():
      button.emoji = '<![play](https://cdn.discordapp.com/emojis/1134067079180464188.webp?size=128 "play")1134067079180464188>'
      await player.pause()
      await interaction.edit_original_response(view=self)
    if player.is_paused():
      button.emoji = '<![pause](https://cdn.discordapp.com/emojis/1134067069848133684.webp?size=128 "pause")1134067069848133684>'
      await interaction.edit_original_response(view=self)

@buoyant quail

slate swan
#

@cloud dawn

#

My code above of these code

warm coral
hasty pike
buoyant quail
slate swan
warm coral
#

a bot?

cloud dawn
hasty pike
buoyant quail
#

So there is only one?

hasty pike
#

@buoyant quail look

buoyant quail
#

errors?

slate swan
cloud dawn
hasty pike
slate swan
#

How I know bro 1k line code

hasty pike
buoyant quail
cloud dawn
slate swan
#

Ok

hasty pike
#

But you have a point

buoyant quail
#

Add prints to check

formal basin
hasty pike
formal basin
#
class PauseButton(discord.ui.View):
   def __init__(self):
      super().__init__(timeout=None)
#rest of code```
slate swan
#

Ctrl+f

#

Show search option

#

@cloud dawn

formal basin
#

how?

hasty pike
#

I have a class but issue is with that specific button

cloud dawn
#

Or just give me the whole raw text if you can't find it.

hasty pike
#

@buoyant quail it printed

buoyant quail
#

Try interaction.response.edit_message
I am not sure about edit_original_response

formal basin
#

yeah

unkempt canyonBOT
#

examples/views/counter.py lines 35 to 36

# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)```
hasty pike
formal basin
#

or do on the command message = interaction.original_response()

#

then do message.edit(content=)

buoyant quail
#

It will take two api calls

hasty pike
#

I tried interaction.edit_message
And still it showed interaction failed and printed too

buoyant quail
#

Do you have error handlers?

hasty pike
formal basin
slate swan
buoyant quail
slate swan
hasty pike
#

Wait I should try it inside try except

slate swan
#

Sorry disturbing bro

cloud dawn
cloud dawn
#

Doesn't look like it I'd need to run this code.

slate swan
#

But these is scrapping file

#

Which scrap answer

cloud dawn
#

I just need one containing the overlapping issue.

hasty pike
#

'interaction' object has no attribute edit_message @buoyant quail

slate swan
#

Which I send

buoyant quail
formal basin
buoyant quail
#

It was not in yours and in mine codes

formal basin
#

i use it

cloud dawn
hasty pike
formal basin
#

ans it works

hasty pike
#

Here

buoyant quail
#

And what i showed you? :p

hasty pike
#

bn_pain response

slate swan
#

Scrapping answer from chegg

cloud dawn
hasty pike
#

Worked now thanks @buoyant quail

cloud dawn
slate swan
#

Beautiful soup

cloud dawn
#

I can't do anything with this code I need the response from the code.

#

I don't want to run this code just to know what text you get.

slate swan
#

I have bot who scrap answer and and send me

#

But in some answer

#

Show isuee which I show in image

cloud dawn
#

I know but you just sent me code. I can't fix the issue if I don't have the raw text from the response.

agile latch
#

Hey I have a purge command that is up and running that however works with a prefix, and I'd like it to be a useable slash command, but cannot figure out how to do it for the life of me... Here's my code :


@client.command()
async def purge(ctx, amount: int):
    if amount > 1000:
        await ctx.send(f"Too many messages to delete ({amount}/1000)")
    else:
        count_members = {}
        async for message in ctx.channel.history(limit=amount):
            if str(message.author) in count_members:
                count_members[str(message.author)] += 1
            else:
                count_members[str(message.author)] = 1
        
        new_string = []
        deleted_messages = 0
        for author, message_deleted in count_members.items():
            new_string.append(f"**{author}**: {message_deleted}")
            deleted_messages += message_deleted
        
        final_string = "\n".join(new_string)
        await ctx.channel.purge(limit=amount + 1)
        
        embedVar = discord.Embed(title=f"{deleted_messages} messages were removed", description="", color=0x00ff00)
        embedVar.add_field(name="Deleted Messages", value=final_string, inline=False)
        embed_message = await ctx.send(embed=embedVar)
        await asyncio.sleep(2)
        await embed_message.delete()```

If someone could help me out that would be awesome
slate swan
cloud dawn
#

It's like giving someone a broken computer and not telling them what the issue is.

cloud dawn
slate swan
#

Ok wait I find

buoyant quail
# agile latch Hey I have a purge command that is up and running that however works with a pref...
GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

Gist

discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.

agile latch
#

<3

cloud dawn
slate swan
#

ok

cloud dawn
#

Anything works.

slate swan
#

<mtext>9 rad/s\xa0</mtext>

cloud dawn
#

Ah makes sense it renders weird.

slate swan
#

yes

#

it add extra thing \xa0

cloud dawn
#

Delete the whole <mtext>9 rad/s\xa0</mtext> or just \xa0?

slate swan
#

actual answer is 9rad/s

#

bro

cloud dawn
#
    def _get_response_text(self, url: str, headers: dict = None, extra_headers: dict = None,
                           expected_status: tuple = (200,), note: str = None,
                           error_note: str = "Error in request", raise_exception=False) -> str:
        """
        text response from web

        :return: Text response from web
        :rtype: str
        """
        logging.debug(msg=f'::getting response from url: {url}')
        response = self._web_response(url=url, headers=headers, extra_headers=extra_headers,
                                      expected_status=expected_status, note=note,
                                      error_note=error_note, raise_exception=raise_exception)
        logging.info(msg=f'::response status code: {response.status_code}')
        if response.status_code not in expected_status:
            raise Exception(f'Expected status code {expected_status} but got {response.status_code}\n{error_note}')
        return response.text.replace("\xa0", "")
#

Just replace that function.

slate swan
#

ok

#

return response.text.replace("\xa0", "")
^
IndentationError: unindent does not match any outer indentation level

C:\Users\HP WORLD\Desktop\d>return response.text.replace("\xa0", "")
'return' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\HP WORLD\Desktop\d> ^
More? IndentationError: unindent does not match any outer indentation level
'IndentationError:' is not recognized as an internal or external command,
operable program or batch file.

#

showing error

cloud dawn
#

Did you copy it correctly?

slate swan
#

yes

cloud dawn
#

Can you send a screenshot?

slate swan
#

ok

#

bro'

#

work

#

/xao

#

not showing

#

but still overlapping

#

turret is zero.\na_barrel_turret = 0 m/s^2\n\n

#

and these \n\n

#

show

cloud dawn
#

It's because you scraped it.

cloud dawn
#

I see but it's overlapped because you don't have mjx-assistive-mml

slate swan
cloud dawn
#

It's not rendered correctly

slate swan
#

storing file on bucket

cloud dawn
#

I'm gonna go to sleep lol
It's a render issue folk over at #web-development are better with this.

cloud dawn
#

Just tell them that mjx-assistive-mml tag isn't rendering correctly.

slate swan
#

thank you so much

agile latch
#

Lots of reading and a few tutorials later, I got a code that doesn't spam errors

#

But the purge command just doesn't work :)

#

@bot.tree.command(name="purge")
@app_commands.describe(message_number='How many messages would you like to delete?')
async def purge(ctx: discord.Interaction, message_number: int):
    if message_number > 1000:
        await ctx.response.send_message(f"Too many messages to delete ({message_number}/1000)")
    else:
        count_members = {}
        async for message in ctx.channel.history(limit=message_number):
            if str(message.author) in count_members:
                count_members[str(message.author)] += 1
            else:
                count_members[str(message.author)] = 1
        
        new_string = []
        deleted_messages = 0
        for author, message_deleted in count_members.items():
            new_string.append(f"**{author}**: {message_deleted}")
            deleted_messages += message_deleted
        
        final_string = "\n".join(new_string)
        deleted = await ctx.channel.purge(limit=message_number)
        
        embedVar = discord.Embed(title=f"{len(deleted)} messages were removed", description="", color=0x00ff00)
        embedVar.add_field(name="Deleted Messages", value=final_string, inline=False)
        embed_message = await ctx.send(embed=embedVar)
        await asyncio.sleep(2)
        await embed_message.delete()```
#

I'm not sure if this might affect it but I set this part at the beginning of my code to be client.event and not bot.event

async def on_ready():
    await tree.sync(guild=discord.Object(id=guildid))
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=f'{status_message}', status=discord.Status.dnd))
    print(f"Logged in as {client.user}")
    channel = client.get_channel(status_channel)
    async for message in channel.history(limit=1):
        global msg_id
        msg_id = message.id
    await asyncio.gather(update())

#got this part off a tutorial, I don't understand the details but I understand that it's what syncs the command between the bot and discord

    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)```
#

Part of the code was made by someone else who used @client.event it's used to interract with a server and is beyond my current scope of understanding, I'm just scared that if I change the wrong shit it will all just break ?

slate swan
#

You shouldn't be making any API calls in on_ready

agile latch
slate swan
#

Make a text command to sync your app commands

agile latch
#

mind if I DM you

slate swan
#

you can also override Client.setup_hook to do async prep work but iirc that gets called before your bot is connected to the gateway so you might get errors or deadlocking

slate swan
#

how to fix

agile latch
slate swan
#

can someone help me, I made a command, with buttons, but when I click them it says "interaction" has no attribute "send"

hasty pike
pure crag
#

is there a better python discord API wrapper out there than discord.py?

slate swan
#

Every is good just preference

sick birch
pure crag
#

eh i phrased that wrong. so im using a very old version of discord.py because i had to go on a forced leave. so im returning and need to rewrite the whole bot because nothing is the same. so at this point im wondering if there's anything i could try to pick up instead of the same old

#

i guess instead of better i mean, basically the same in terms of ease of use

sick birch
#

I would recommend discord.py simply because it's the most used and therefore has the most community support

#

You'll have a much higher chance of getting help with discord.py if you get stuck or need help

slate swan
sick birch
#

But ever since the incident there have been other libraries popping up which previous didn't stand a chance

pure crag
#

yeah i know theres a bunch now. i just wanna experiment ig

#

but out of those, whats good?

sick birch
pure crag
#

whats bad about pycord?

sick birch
#

if you're looking for something completely new try Hikari

#

Bad community + bad library

pure crag
#

i just noticed pycord has the most starts below discord.py

#

ah

pure crag
hasty pike
unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
slate swan
# hasty pike !d discord.InteractionResponse.send_message
@bot.event
async def on_button_click(interaction):
    if interaction.custom_id == "command2":
        await interaction.send_message("You clicked on Command 2 button!", ephemeral = False)
    elif interaction.custom_id == "command3":
        await interaction.send_message("You clicked on Command 3 button!", ephemeral = False)

isnt working :(

hasty pike
#

That's not how you respond to button

slate swan
# hasty pike That's not how you respond to button

then how...

@bot.command()
async def test(ctx):
    embed = discord.Embed(title="Help Command", description="List of available commands:")
    embed.add_field(name="Command 1", value="Description of command 1", inline=False)
    embed.add_field(name="Command 2", value="Description of command 2", inline=False)
    embed.add_field(name="Command 3", value="Description of command 3", inline=False)

    class HelpView(View):
        def __init__(self):
            super().__init__()

        async def on_timeout(self):
            self.stop()

    class HelpButton(Button):
        def __init__(self, user):
            super().__init__(style=discord.ButtonStyle.primary, label="Command 1", custom_id="command1")
            self.user = user

        async def callback(self, interaction: discord.Interaction):
            if interaction.user == self.user:
                await interaction.send_message("You clicked on Command 1 button!")
            else:
                await interaction.send_message("You are not allowed to click this button!")

    view = HelpView()
    view.add_item(HelpButton(ctx.author))
    view.add_item(Button(label="Command 2", custom_id="command2"))
    view.add_item(Button(label="Command 3", custom_id="command3"))

    await ctx.send(embed=embed, view=view)```
sick birch
hasty pike
#

Indentation

#

Can we make view class inside command? @sick birch

sick birch
#

yes

hasty pike
#

Oh

sick birch
#

You can make classes inside functions and even inside other classes

#

It's not recommended but it's syntactically correct

hasty pike
#

Learnt something new today,๐Ÿ˜‚

hasty pike
slate swan
#

now discord isnt logging in via static token

#

it stays on that

#

2023-07-28 021640 INFO discord.client logging in using static token
2023-07-28 021736 INFO discord.gateway Shard ID None session has been invalidated.

sick birch
hasty pike
slate swan
#

there we go

#

internet being buggy

slate swan
#

im using this for my help command, with buttons, so you can select certain categories

#

nevermind.

unique lichen
#

can someone explain how do i correct this error?

slate swan
#

i didnt give 2

sick birch
#

Can you show your code?

slate swan
#
       async def callback(self, interaction: discord.Interaction):
            if interaction.user == self.user:
                await interaction.edit_original_response('You clicked on Command 1 button!')
            else:
                await interaction.response.send_message("You are not allowed to click this button!")```
#

thats where im getting the error

sick birch
#

If you meant to edit the content of a message, you need to specify that:

await interaction.edit_original_response(content="New content")
slate swan
#

ohhhhh

slate swan
unique lichen
sick birch
#

you have to specify that too, embed=my_embed where my_embed is your embed

slate swan
#

.-.

#

i give up

slate swan
slate swan
slate swan
upbeat gust
#

Is this a subclass of ui.Button? you'd set it in __init__

loud bronze
#

does anyone have the documentation for python discord bot thing?

turbid condor
loud bronze
#

im just looking for anything , what library would you recomend for discord bots?

naive briar
#

discord.py, obviously

loud bronze
#

mb

turbid condor
#

discord.py is a good one if u want to build a discord bot

#

But inorder to create a discord bot using u will need to have an understanding of oops

dry sedge
#

How do I make my bot so that it starts multiple websocket connections in the same call so I can have like different instruments playing without overlapping its like a different voice call for each instrument with the same bot in the same voice call

turbid condor
#

Wouldn't that get you rate limited pretty quick?

sick birch
rugged shadow
unique lichen
rugged shadow
#

sync your clock

#

if you're using Windows it shld be here

hushed galleon
# unique lichen can someone explain how do i correct this error?

apparently its trying to sleep until a datetime which has already been 10 minutes in the past
what's your code? how did you specify the time for your loop? are you using discord.py 2.0 or a different library like pycord?

looking through dpy's source i cant comprehend how this is possible in the first place, so having details to reproduce the bug would be helpful

graceful basin
#

hey yall! i gotta question...how can i add buttons in my discord bot using discord.py?

#

i found something called discord-components, but i cant download it on vscode, was wondering if its maybe outdated?

hushed galleon
graceful basin
#

whats an alternative?

hushed galleon
#

you'll need to upgrade to dpy 2.0 to use those message components

graceful basin
#

what can i use for that

#

cani use ui too

hushed galleon
frosty beacon
#

I want to implement the following feature:

me: !ban
bot: reason
me: gives reason
bot: how many days!
me: days
bot: send dm.
me: y/n
bot: done
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.11)"). 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.11)") 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.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

you're gonna want to use this iirc

frosty beacon
#

ok, but how do I create the conversation session. after invoking !ban cmd

slate swan
#

are you sure that's the way you want to make the command?

#

You could just make it require those arguments

frosty beacon
#

maybe, we first listen to cmd to initiate and then start a listing session with user

#

it can be helful if i want to add Ai chatbot

frosty beacon
# slate swan I have no clue what you mean

lets say I want to make a chatbot.
!start will initiate the session with user. means bot will listen msg send by user in that channel. and reply to him
!stop to terminate the session.

slate swan
#

I would reccomend you instead just add reason and time as an argument

frosty beacon
slate swan
#

anyone can ban anyone if you do that

frosty beacon
#

but its for friend group. not public.

slate swan
#

I see

frosty beacon
#

any clue

slate swan
#
@bot.command()
async def ban(ctx: commands.Context) -> None:
    await ctx.send("Reason for ban?")
    check = lambda msg: msg.author == ctx.author
    response = await bot.wait_for("message", check=check)
    await ctx.send(f"Reason set as: {response.content}")
    # continue
#

You'd want to do something like this

#

I think you can understand the logic

frosty beacon
#

yep, its not quite useful for QnA bot

slate swan
#

you're gonna probably want a listener for that

frosty beacon
#

yes. trying to figure that out

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
wispy pasture
#

yeah so the perms are a bit messed up here:

yeah so the perms are a bit messed up here:
 overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=True, send_messages=False),
            r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),
            interaction.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)
        }```

right now when the button to close a ticket is sent the ticket becomes public and everyone can view it, edit the code so only the person who opened the ticket can view it
i want the user who opened the ticket to be able to see the ticker; but not send a message in it
sharp whale
#
class TicketModal(ui.Modal, title="Tickets"):
        inputissue = ui.TextInput(label="Explain your issue",
                                  style=discord.TextStyle.paragraph)
        async def on_submit(self, interaction):
            guild = interaction.guild
            moderator_role = guild.get_role(config.mod_role)
            overwrites = {
                guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True),
                moderator_role: discord.PermissionOverwrite(view_channel=True)
            }
            category = discord.utils.get(guild.categories, id=config.TICKET_CATEGORY)
            channel = await category.create_text_channel(f"ticket-{interaction.user.name}", overwrites=overwrites)
            await interaction.response.send_message(f"Ticket created {channel.mention}")```
#

wheres the problem

#

Its sending the modal, but the submit button isnt working

naive briar
#

isnt working doesn't explain the problem

sharp whale
#

._.

#

im using cogs so i dont get errors

buoyant quail
#

Cogs aren't doing anything with the errors

#

If you have error handlers - disable them then.

sharp whale
buoyant quail
#

what

sharp whale
#

eh

buoyant quail
#

you are running multiple bots?

sharp whale
#

cogs

buoyant quail
#

then why would you get error somewhere else

sharp whale
#

ok i removed the modal, still cant create the channel

sharp whale
buoyant quail
#

it doesn't matters

#

all errors will be in the place from where you are calling it

sharp whale
#

how would i get the error if i run main.py and access a different file for commands and still get the errors on the terminal

#

!paste

sharp whale
sharp whale
#

i dont get errors when i load the cog

#

if i Restart the bot or reload the cog, i get error

#

but, if i run the command i dont get the errors

naive briar
#

Set its callback before adding it to the view, or better yet, just subclass the view and get rid of that mess

buoyant quail
naive briar
#

What?

buoyant quail
buoyant quail
#

You have error handlers i guess.

sharp whale
#

yes

buoyant quail
#

Then you should print out the error there

#

If you don't do something with error inside error handler, it is just dropped

sharp whale
#

i have

#

print

buoyant quail
#

Show it

cloud dawn
#

Why make an error handler and pass all exceptions pithink

sharp whale
#

except Exception as e:
print(e)

#

like this

buoyant quail
#

except?

#

What does it make inside an error handler

#

Show your full error handler

sharp whale
cloud dawn
#

lmao

buoyant quail
#

lmao

sharp whale
#

wha

cloud dawn
#

A for effort tough

sharp whale
#

what

sharp whale
buoyant quail
#

That try-except will work only when you are killing the process (stopping the bot)

sharp whale
#

oh

#

I removed the error handler

#

I still dont get the errors

buoyant quail
#

Do you have an actual error handlers?
Like on_error or something like this

sharp whale
#

no

naive briar
#

Totally not because there's no logging setup

slate swan
#

setup logging

wheat laurel
#

hey? do you know how to make music bot

sharp whale
cloud dawn
#

You can't just put every command inside a try except.

wheat laurel
#

ะตะผะฐะต

naive briar
#

!d discord.utils.setup_logging

cloud dawn
#

!rule 4

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.

New in version 2.0.
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

slate swan
sharp whale
naive briar
#

What example? The function is as easy to use as a function can be, just call it

naive briar
#

Before starting the bot

sharp whale
#

buthow

naive briar
#

Call it

sharp whale
#

like, what will it go are the parameters

naive briar
#

They are all optional

#

And what can go there is explained in the docs

sharp whale
cloud dawn
#

log it*

naive briar
#

If you mean logs, the function already handle all that

sharp whale
#

so i only have to all the function

#

but how

naive briar
#

How what

sharp whale
#

ehhh

#

tell me how would i do it

naive briar
#

Do what

sharp whale
#

like,

@bot.event
async def on_error():
    pass```
#

or how

cloud dawn
#

He told you 5 times already.

sharp whale
#

eh

#

my brain is so smol sorry

cloud dawn
#

Call the function before starting the bot.

sharp whale
#
await on_error()```
#

like this?

cloud dawn
#

What does on_error have to do with this?

sharp whale
#

eh

cloud dawn
#

We're talking about logging.

sharp whale
#

how would i do it

cloud dawn
sharp whale
#

how would i call it

cloud dawn
#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.

New in version 2.0.
naive briar
#

Like any other functions

cloud dawn
sharp whale
#

what

frosty beacon
cloud dawn
left mantle
#

can someone help me with my discord bot please? i've never seen this error before and i'm stumped

slender kraken
#

Hello, I haven't used this application in a while and I think the version may have updated.. What is a way I can import discord to my bot? I used to use import discord but i get an error.

left mantle
left mantle
cloud dawn
slender kraken
#

ohh

left mantle
slender kraken
#

thanks

slate swan
buoyant quail
#

And you'd need to send the link to that library
Because i can't find it

left mantle
#

the thing is i didn't even import that library

buoyant quail
#

You have import from twitch.api import API
That library has absolutely different imports

left mantle
#

these are the only things ive imported

import os
from discord.ext import commands
from twitch import TwitchClient```
buoyant quail
#

It is still different from what the examples are showing
And your error says that your 4 line is not like that.

left mantle
#

well that's what my line 4 is

buoyant quail
left mantle
#

i have no idea how it's outputted that

buoyant quail
#

You didn't save the file mb
Or running some different file

left mantle
#

wait i refreshed it and now it says from twitch import TwitchClient

#

weird

#

this is the updated version

buoyant quail
#

The library you sent uses name twitchAPI
There is no just twitch there

left mantle
#

oh

#

uhm i don't know then

#

i dont really use twitch libraries

slate swan
#

so how did you come up with this code

left mantle
#

wait

buoyant quail
#

accidentally imported twitch grumpchib

left mantle
#

i sent the wrong library

#

should be that one

buoyant quail
#

Seems so.
But there is no TwitchClient there.

sharp whale
#

@buoyant quail what error did u get when u ran my code

buoyant quail
left mantle
#

my mate said i need TwitchClient in the code for something can't remember what

left mantle
#

do you think it might be that fact that i've installed python-twitch, twitch-python and python-twitch-client?

#

using pip

buoyant quail
#

I don't know which library and methods you want to use ยฏ_(ใƒ„)_/ยฏ

buoyant quail
#

python-twitch-client does have it

left mantle
#

ive just looked at docs and it says from twitch import TwitchClient

#

that's the library that's i've downloaded

buoyant quail
#

If it is the library that you've downloaded...
You have sent a lot of others

#

Uninstall all of them and install only needed

left mantle
#

okay done that

#

i only have python-twitch-client installed now

buoyant quail
#

then it shouldn't give the error

left mantle
#

i didn't get the error but i got a different one

buoyant quail
#

try from twitch.client import TwitchClient mb

#

Actually it works fine with just from twitch import TwitchClient

#

It's something by you

#

Check that it's installed correctly

naive briar
#

They probably have a folder named twitch

left mantle
#

i dont

vocal snow
left mantle
#

nope

left mantle
#

i've just uninstalled and reinstalled python-twitch-client and it fixed it, i had an intents error but i know how to fix those

#

thanks for the help guys

left mantle
#

just ran the command and now i have a new error, i'll send the code and the error

#
import discord
import os
from webserver import keep_alive
from discord.ext import commands
from twitch import TwitchClient

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

twitch_client = TwitchClient()

@client.command()
async def update_followers(ctx, twitch_username):
    user = twitch_client.users.get_by_login(twitch_username)
    follower_count = user.followers

    guild = ctx.message.guild
    voice_channel = guild.get_channel(1042079613339312148)
    new_name = f"{twitch_username} - {follower_count} followers"
    await voice_channel.edit(name=new_name)

keep_alive()
token = os.environ['TOKEN']
client.run(token)```
naive briar
#

Let me guess, undefined name?

#

Nvm, just saw it

worthy heart
#

how can I get a list of all slash commands and their IDS

I used to be syncing the bot on_ready but then I discovered it is a really bad idea

so how can I get the same output that client.tree.sync() returns?

naive briar
#

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
worthy heart
#

I have tried client.tree.walk_commands() but it doesn't return the slash commands ID

#

there's no id attribute

naive briar
#

It returns an iterator of app_commands.Command objects

#

!d discord.app_commands.Command

unkempt canyonBOT
#

class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.

These are usually not created manually, instead they are created using one of the following decorators:

โ€ข [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command "discord.app_commands.command")

โ€ข [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command "discord.app_commands.Group.command")

โ€ข [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command")...
worthy heart
#

I know, looping through it, the command doesn't have an id attribute

left mantle
#

went to go do something here's the error

naive briar
unkempt canyonBOT
#

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

Fetches the applicationโ€™s current commands.

If no guild is passed then global commands are fetched, otherwise the guildโ€™s commands are fetched instead.

Note

This includes context menu commands.
naive briar
#

!d discord.app_commands.AppCommand.id

unkempt canyonBOT
naive briar
#

That's the one

left mantle
slate swan
#

can anyone help me with this mini game thing im trying to make for my bot? it, kinda half works

naive briar
#

What's the problem?

worthy heart
worthy heart
left mantle
buoyant quail
#

xdd

naive briar
#

Why don't just find an equivalent one in the current library you're using

exotic island
cyan grove
#

im trying to make my bot send emoji with a message but I am struggling. Can someone give me an example of how to add, lets say a thumbs up( ๐Ÿ‘ ), emoji to the messages my bot would send? Please @ me when you reply. Thanks in advance

slate swan
#

its how to add reaction but logic how to get emoji is the same

cloud dawn
#

message.add_reaction("๐Ÿ‘")

cyan grove
#

i might have not done it properly

#

i tried to do something like this

cyan grove
#

i wanted to add dog emoji but I did not implement properly

slate swan
#

i think it will be easier and more readable when you use unicode emojis

#

meaning this

#

or if its not default emoji use the emoji string emoji = '![python3](https://cdn.discordapp.com/emojis/232720527448342530.webp?size=128 "python3")'

cyan grove
#

so something like

message = "๐Ÿ‘"

and then i pass the message ?

slate swan
#

can be

cloud dawn
#

Just use a constants file.

#

Emoji.thumbs_up is way cleaner

cyan grove
cloud dawn
#

A constants file is a file containing frequently used strings or a set of characters.

slate swan
#

example of @unkempt canyon bot

cloud dawn
#

It's good since if you change it in the constants it changes everywhere.

unkempt canyonBOT
#

bot/constants.py lines 514 to 519

class _Emojis(EnvConfig):
    EnvConfig.Config.env_prefix = "emojis_"

    badge_bug_hunter = "![bug_hunter_lvl1](https://cdn.discordapp.com/emojis/743882896372269137.webp?size=128 "bug_hunter_lvl1")"
    badge_bug_hunter_level_2 = "![bug_hunter_lvl2](https://cdn.discordapp.com/emojis/743882896611344505.webp?size=128 "bug_hunter_lvl2")"
    badge_early_supporter = "![early_supporter](https://cdn.discordapp.com/emojis/743882896909140058.webp?size=128 "early_supporter")"```
slate swan
#

example snippet of emojis constants

cyan grove
#

lets say i want to implement a dog emoji

#

i do something like

doggo = "<:dog: <NUMBERS> >"
#

i dont understand the numbers bit tho

slate swan
#

and the numbers are the emoji id

cyan grove
#

okkkk

#

i am not planning to use custom emojis

slate swan
#

how to get this "numbers": ```py
The name and ID of a custom emoji can be found with the client by prefixing :custom_emoji: with a backslash. For example, sending the message :python3: with the client will result in python3.

cyan grove
#

:python3:

#

huh

slate swan
#

the emoji must exist

naive briar
slate swan
cyan grove
#

oooooo nice

cloud dawn
slate swan
#

and when you do this with built in emoji

#

it will return unicode icon

cloud dawn
#

\๐Ÿ‘

slate swan
#

\๐Ÿถ

cloud dawn
#

It's like people made it to behave that way.

cyan grove
slate swan
#

no just copy the emoji from discord and paste it as string

cyan grove
#

makes sensse

slate swan
#

dog = "๏ฟฝ"

#

shouldnt be question mark when you do that in your ide

cloud dawn
#

๏ฟฝ

cyan grove
#

alr makes sense

#

lemme try now

#

i will be back

cloud dawn
#

!charinfo ๏ฟฝ

unkempt canyonBOT
cloud dawn
#

!charinfo ๐Ÿถ

unkempt canyonBOT
#
Character Info

\U0001f436: DOG FACE - ๐Ÿถ

cyan grove
#

it works!!!!!!

slate swan
cyan grove
#

lets gooooooooooooooooo im so pumped

#

thanks @slate swan @cloud dawn

#

you guys are awesome

cloud dawn
#

Just Down, I'm only here to annoy him.

#

My sole duty.

cyan grove
#

lmao

slate swan
cyan grove
#

i love how my bot is coming together. I can now get random xkcd comics when i use a command

cloud dawn
#

Imagine Nitro smh

cyan grove
slate swan
cloud dawn
#

I want to reply so bad to this but the ToS gods will smite me.

slate swan
cyan grove
#

I wanted to get random Calvin and Hobbes comic strips through my bot but I couldn't find any proper APIs

cyan grove
cyan grove
cyan grove
#

ahahhaha

cloud dawn
#

Lol

slate swan
#

you are missing function below it

#

you didnt create Client instance

hushed galleon
#

did you save your file before running it? you would have gotten a syntax error if there really wasnt a function under the decorator

#

ah nvm

cloud dawn
#

You have to call Client and set Intents.

#

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

left mantle
#

i have a problem with my code, does anyone know how to fix this error? TypeError: 'async_generator' object is not scriptable

#

i'll send the code aswell

#
import os
import discord
from webserver import keep_alive
from discord.ext import commands
from twitchAPI.twitch import Twitch

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
twitch_client = Twitch(os.environ.get('TWITCH_CLIENT_ID'), os.environ.get('TWITCH_CLIENT_SECRET'))

@client.command()
async def update_followers(ctx, twitch_username):
    user = twitch_client.get_users(logins=[twitch_username])
    if not user['data']:
        await ctx.send(f"{twitch_username} does not have a Twitch channel.")
        return
    user_id = user['data'][0]['id']
    channels = twitch_client.get_streams(user_ids=[user_id])
    if not channels['data']:
        await ctx.send(f"{twitch_username} channel is currently offline.")
        return
    follower_count = channels['data'][0]['viewer_count']
    name = f"{twitch_username} - {follower_count} followers"
    try:
        voice_channel = await client.fetch_channel(104295318813478400)
        await voice_channel.edit(name=name, reason="Updating follower count.")
        await ctx.send(f"Successfully updated follower count for {twitch_username} to {follower_count}.")
    except discord.errors.HTTPException as e:
        await ctx.send("Failed to update follower count. Check if the bot has permissions to edit the channel name.")
        
keep_alive()
token = os.environ['TOKEN']
client.run(token)```
upbeat ice
#

looks like twitch_client.get_users is async

#

so you should be awaiting that

left mantle
#

i'm getting the error with this snippet of code if not user ['data']:

upbeat ice
#

well yes

#

read what I said ๐Ÿ˜›

buoyant quail
#

also i wonder why you expect getting one user from function get_user__s__

#

also it returns a class, not a dictionary (and that class has no __getitem__ as i see)

left mantle
#

so i thought that would've worked

left mantle
upbeat ice
#

show your code

upbeat ice
finite geyser
buoyant quail
#

I am not sure if async generators can be just awaited

#

You need to use an async for for them

upbeat ice
#

or use the first() helper

buoyant quail
#

Or the thing that is in the first example

#

Yeah

slate swan
#

You do use async for

upbeat ice
#

he also needs to be using await for Twitch()

buoyant quail
#

interesting that he got no errors about that one

#

ahh, tf

#

understood

unkempt canyonBOT
#

twitchAPI/twitch.py lines 271 to 275

def __await__(self):
    if self._authenticate_app:
        t = asyncio.create_task(self.authenticate_app(self._target_app_scope if self._target_app_scope is not None else []))
        yield from t
    return self```
upbeat ice
#

well thats interesting

left mantle
buoyant quail
#

Of course not

left mantle
#

oh

upbeat ice
#

is there a reason why you dont want to use the first() helper function?

buoyant quail
#

async for is the same loop as for

buoyant quail
left mantle
left mantle
upbeat ice
#

looks as simple as user = await first(twitch_client.get_users(logins=[twitch_username]))

buoyant quail
buoyant quail
#

Gets one user by name and prints id

upbeat ice
#

light mode ๐Ÿ˜ฎ

slate swan
#

can you add hypertext in embed title? like not url kwarg but text with hypertext

upbeat ice
#

i always just use the url kwarg but let me try

slate swan
#

i just want part of it

slate swan
#

and cant really test it rn

upbeat ice
#

ill try after my meeting

slate swan
#

nw

formal basin
#
@client.listen()
async def on_member_update(before, after):
   
     if after.id == client.user.id:
        return
     if after.nick == "Bad word name":
       pass
     else:
         key = f'antibadwords:{before.guild.id}'
         if r.exists(key):
           if profanity.contains_profanity(after.nick) or profanity.contains_profanity(replaceDoubleCharacters(after.nick)):
            new_nickname = "Bad word name"  
            await after.edit(nick=new_nickname) 
            log = r.get(f"logs:{str(after.guild.id)}")
            embed = discord.Embed(title="nickname changed", description=f"{after.mention}'s nickname was changed")
            embed.add_field(name="Reason", value="contained bad words")
            embed.set_footer(text="Censored by better_profanity")
            log2 = int(log.decode("utf-8"))
            logging = client.get_channel(log2) or await client.fetch_channel(log2)
            await logging.send(embed=embed)
            print(f"1bad word detected logs: {after.guild.id}")
       ``` if someone joins it changes their name to bad word name even though its not a bad word
buoyant quail
#

and what contains_profanity and replaceDoubleCharacters are?

pure crag
#

would anyone like to help work on a brand new Discord API wrapper?

sick birch
#

those are generally considered difficult

pure crag
#

yes

#

its not discouraging me though. its happening regardless

sick birch
devout drum
#

getting errors for these how do i fix it

buoyant quail
#

And what's the error?

slate swan
#

probably not installed?

devout drum
#

my commands dont work now tho

#

i can send the code

proper thicket
slate swan
devout drum
#

bot is not responding

devout drum
#

it was the bot token

slate swan
#

yo so im having a problem when i go to type my command nothing happens but it doesnt look like there is any problems with my bot when i put it up

#

this is all i see i dont know if it means anything

devout drum
slate swan
devout drum
slate swan
devout drum
#

damn

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

devout drum
#

what r u usin the bot for, im only in this code for discord bots personally mines for a shop

finite geyser
#

use venv

turbid condor
#

!pip discord

unkempt canyonBOT
finite geyser
#

both works fine

sick birch
#

presumably to prevent typosquatting

devout drum
finite geyser
#

good

swift siren
#

iโ€™ve installed it n i keep getting the same error

turbid condor
swift siren
#

i already had it installed

glad cradle
#

if you're on windows you can do

py -3.10 -m pip install -U discord.py[voice]

you can replace the 3.10 with the python version that you're using

glad cradle
#

what

devout drum
#

i did pip install discord.py and pip install discord-py-slash-command

slate swan
#

You know discord.py Has slash commands built in already

#

You dont need external module

#

in the source code

#

it provides an instance already

frosty beacon
#

where the instance is get created??

naive briar
#

What

slate swan
unkempt canyonBOT
#

discord/state.py lines 1619 to 1620

def create_message(self, *, channel: MessageableChannel, data: MessagePayload) -> Message:
    return Message(state=self, channel=channel, data=data)```
slate swan
#

if you are trying to create message object yourself there are methods for this

#

!d discord.abc.Messageable.fetch_message

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/latest/api.html#discord.Message "discord.Message") from the destination.
buoyant quail
digital magnet
#

Yo @rancid grail
can you guys update discord library?
so we can send ephemeral messages by using that library?

rancid grail
digital magnet
buoyant quail
#

idk if that's what you mean, but you can send ephemerals in discord.py

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
buoyant quail
#

ephemeral arg

gloomy hound
#

Do you think this is a good structure for a command based bot ?

#

everythink is made with classes except main.py which contains 4 lines

#

basically it's a .run with the token loader

#

btw I'm using pycord

frosty beacon
digital magnet
frosty beacon
#

whrer??

digital magnet
#

idk

#

but i do think i saw you somewhere

frosty beacon
#

k

slate swan
frosty beacon
buoyant quail
unkempt canyonBOT
#

discord/state.py lines 619 to 620

message = Message(channel=channel, data=data, state=self)  # type: ignore
self.dispatch('message', message)```
digital magnet
#

is it like this

#
await ctx.send("This is an ephemeral message!", ephemeral=True)```
frosty beacon
buoyant quail
digital magnet
buoyant quail
#

Reaction is not an interaction

#

With buttons you can

shrewd apex
gloomy hound
#

is it bad ?

shrewd apex
#

why seperate files for embeds

gloomy hound
#

idk

shrewd apex
#

is one file not enough for all the embeds

buoyant quail
#

Super speed optimization pithink

gloomy hound
#

why not

shrewd apex
digital magnet
gloomy hound
#

so

#

40 x 30 lines

#

it's a lot

shrewd apex
#

why do u need 40 embed classes why u need sn embed class if first place

buoyant quail
digital magnet
shrewd apex
#

what does it fo for the embed

gloomy hound
digital magnet
shrewd apex
#

so why not just a single embed class with static methods which returns embed instances

gloomy hound
#

wdym

glad cradle
#

the best solution for embeds is to store them as dicts

gloomy hound
#

but

#

actually the behavior is stored into the embed

#

like I have chatgpt embed

digital magnet
gloomy hound
#

And all the requests, stuff is in the embed class

glad cradle
#

ah

digital magnet
shrewd apex
#

weird but ok then ig

glad cradle
#

Well then it's not just an embed if it handle some other logic

gloomy hound
shrewd apex
#

i like having logic and ui seperated

glad cradle
shrewd apex
digital magnet
#

guys if i wrote a 400 lines of discord bot , am i pro discord maker then?

glad cradle
gloomy hound
glad cradle
#

when I didn't know what cogs and extensions were I wrote a bot of 800 lines

#

with blocking code as well

#

it was my dark era

shrewd apex
shrewd apex
glad cradle
digital magnet
buoyant quail
#

i believe

buoyant quail
#

it's not a lot

digital magnet
digital magnet
#

bye ( everyone dead rn )

slate swan
left mantle
#

hello, i'm getting the error below but i'm using the helix api not the kraken api, how do i fix it? here's the code and error:

client = TwitchClient(
    client_id = os.environ['TWITCH_CLIENT_ID'], 
    oauth_token = os.environ['TWITCH_OAUTH_TOKEN'])
users = client.users.translate_usernames_to_ids(['graveyardztv', 'coinzplayz'])
for user in users:
     print('{}: {}'.format(user.name, user.id))
naive briar
#

I don't think this is Discord bot related, I'd recommend posting your question in #1035199133436354600 instead

left mantle
#

i'll get there eventually i just want to make sure that it actually returns the follow amount before i start that

#

i'll post it in python-help in hopes for help

naive briar
left mantle
#

okay, sorry

slate swan
#

hi

#

i need help for my script it say that

#

how do i turn into used

naive briar
#

Use it ๐Ÿคท

slate swan
#

how

naive briar
#

Use it, I said it

#

If you defined something and leave it unused, it's kinda pointless

slate swan
#

i was using this script before it was perfect wat appen

#

i need to use it on the script ?

slate swan
#

requests package != resquest package

sharp whale
#

!paste

sharp whale
sharp whale
slate swan
#

or i need to use it in my code

sharp whale
slate swan
#

ok thank !

naive briar
slate swan
#

thank

sharp whale
slate swan
#

dam wt wrong with da line 44

sharp whale
slate swan
sharp whale
#

privilaged intents ._.

slate swan
#

wt the eror say

#

im bad

sharp whale
cloud dawn
#

Read the error then you will know

sharp whale
sharp whale
slate swan
#

oh dam

#

ok

sharp whale
#

yes

cloud dawn
sharp whale
#

:D

slate swan
sharp whale
#

wao

cloud dawn
#

Hmm nevermind it's crying about the permissions.

shrewd apex
#

lots of pandas here

young dagger
#

You misspelled it

shrewd apex
#

wasn't the package name requests

finite salmon
#

You shouldn't be using request for discord bots anyway

shrewd apex
#

!pypi requests

unkempt canyonBOT
shrewd apex
#

aiohttp ^^

sharp whale
#

its requests

shrewd apex
#

ye

young dagger
sharp whale
#

wha

finite salmon
#

requests a non async

shrewd apex
#

just say its sync ๐Ÿ—ฟ

young dagger
exotic island
cloud dawn
#

@sharp whale Does moderator_role have an .id attribute? It's trying to get all .id's from all permission targets.

finite salmon
# sharp whale wha

basically it won't "run in the background" when u use it but instead it'll block the entire process of the bot until it finishes

finite salmon
sharp whale
cloud dawn
# sharp whale the moderator role is itself a snowflake
async def selectmenu_callback(interaction):
    print([x.id for x, y in overwrites.items()])
    creator = interaction.user
    category = discord.utils.get(guild.categories, id=config.TICKET_CATEGORY)
    channel = await category.create_text_channel(f"ticket-{creator.display_name}", overwrites=overwrites)
    await interaction.response.send_message(f"Ticket created {channel.mention}", ephemeral=True)
#

@sharp whale I assumed you fixed it?

sharp whale
#
overwrites ={
                    guild.default_role: discord.PermissionOverwrite(view_channel=False),
                    interaction.user: discord.PermissionOverwrite(view_channel=True),
                    moderator_role: discord.PermissionOverwrite(view_channel=True)
                }```
#

this is my overwrites

cloud dawn
#

I know.

cloud dawn
sharp whale
#

wait

#

@cloud dawnpy Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in selectmenu_callback print([x.id for x, y in overwrites.items()]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in <listcomp> print([x.id for x, y in overwrites.items()]) ^^^^ AttributeError: 'NoneType' object has no attribute 'id'

cloud dawn
#

hmm we need to isolate the one that does not have a .id

sharp whale
#

Mr. Turtle typing

slate swan
#

how about you do ```py
for item in overwrites.items():
if not getattr(item, "id", None):
print(item)

naive briar
#

!e

getattr(None, "id")
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     getattr(None, "id")
004 | AttributeError: 'NoneType' object has no attribute 'id'
cloud dawn
#

Before the overwrites add this ```py
print(guild.default_role.id, interaction.user.id, moderator_role.id)

slate swan
#

nope it raises

naive briar
#

Set a default value

slate swan
#

yeah updated code

naive briar
#

Or use hasattr instead

cloud dawn
slate swan
naive briar
#

Haven't thought about it either ducky_skull

slate swan
#

!e print(hasattr(None, "id"))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
cloud dawn
#

It's a Nonetype object so it doesn't have hasattr.

slate swan
#

but hasattr isnt a method

sharp whale
#

@cloud dawnpy Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in selectmenu_callback print([x.id for x, y in overwrites.items()]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 80, in <listcomp> print([x.id for x, y in overwrites.items()]) ^^^^ AttributeError: 'NoneType' object has no attribute 'id' [2023-07-29 19:26:20] [ERROR ] discord.ui.view: Ignoring exception in view <View timeout=None children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Open Ticket' emoji=<PartialEmoji animated=False name='๐Ÿ“ฉ' id=None> row=None> Traceback (most recent call last): File "C:\Users\jpash\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "e:\honey\Programming\BOTS\Dart Nodes new\commands\tickets.py", line 35, in ticket_callback print(guild.default_role.id, interaction.user.id, moderator_role.id) ^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'id'

cloud dawn
#

Called it

slate swan
#

moderator_role ๐Ÿง

naive briar
#

!e

print(hasattr(None, "id"))
unkempt canyonBOT
#

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

False
cloud dawn
#

Something is wrong with the moderation_role

sharp whale
#
moderator_role = guild.get_role(config.mod_role)```
#

this is the moderator_role

slate swan
#

looks like it returns None

cloud dawn
#

What is config.mod_role?

sharp whale
#

and it pings it when i do <@&id>

slate swan
#

if get_role returns None you might thing of using the fetch_role

cloud dawn
#

Just create a snowflake then.

slate swan
cloud dawn
#

discord.Object(config.mod_role)

cloud dawn
slate swan
#

ah so he doesnt need the Role object

cloud dawn
#

Just the .id attr

slate swan
#

then why use get_role using id just to access id attr

cloud dawn
#

Dunno

sharp whale
#

wha

cloud dawn
# sharp whale wha

Well you didn't understand the traceback most likely, wich I understand but if you look up the line inside the source you can see what it does and where the issue might be.

sharp whale
#

oh

cloud dawn
sharp whale
#

so i dont have to get the role?

#

only snowflake?

cloud dawn
#

No since the overwrites only need the id nothing else.

sharp whale
#
overwrites ={
                    guild.default_role: discord.PermissionOverwrite(view_channel=False),
                    interaction.user: discord.PermissionOverwrite(view_channel=True),
                    config.mod_role: discord.PermissionOverwrite(view_channel=True)
                }```
cloud dawn
#

That's not what I meant.

sharp whale
#

uhh

cloud dawn
#

You need the .id attr since it will use target.id

sharp whale
#

how

#

the role has .id attr

cloud dawn
#

You just told me mod_role is just the id?

sharp whale
#

yes

cloud dawn
#

Is mod_role an int or a snowflake?

sharp whale
#

thats why i used get_role()

sharp whale
cloud dawn
#

Okay look lemme visualize

sharp whale
#

int and snowflake same things right?

cloud dawn
#
def _create_channel(
    self,
    name: str,
    channel_type: ChannelType,
    overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
    category: Optional[Snowflake] = None,
    **options: Any,
) -> Coroutine[Any, Any, GuildChannelPayload]:
    if overwrites is MISSING:
        overwrites = {}
    elif not isinstance(overwrites, Mapping):
        raise TypeError('overwrites parameter expects a dict.')

    perms = []
    for target, perm in overwrites.items():
        if not isinstance(perm, PermissionOverwrite):
            raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')

        allow, deny = perm.pair()
        payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}

        if isinstance(target, Role):
            payload['type'] = abc._Overwrites.ROLE
        else:
            payload['type'] = abc._Overwrites.MEMBER

        perms.append(payload)

    parent_id = category.id if category else None
    return self._state.http.create_channel(
        self.id, channel_type.value, name=name, parent_id=parent_id, permission_overwrites=perms, **options
    )
``` this is the create role function
#

Look at this line for target, perm in overwrites.items():

#

target will be all the key values of the overwrites dictionary.

sharp whale
#

what

cloud dawn
#

Then it will go to payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}

#

Where target is all the different key values inside the overwrites. And it will try to get the attr id.

sharp whale
#

uhhh

cloud dawn
#

Is this possible?

sharp whale
#

no