#discord-bots

1 messages Β· Page 204 of 1

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
#

breh

#

and their isnt a trace back @sick birch

sick birch
#

Do you have any other files?

slate swan
#

acc wait

sick birch
#

Check your console

#

There should be error logs

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
sick birch
#

It doesn't seem like you even have a callback for your button

frosty parrot
#

what's the problem here ```import discord
from discord.ext import commands

class cogs(commands.Cog):
def init(self, client):
self.client = client

def setup(bot):
    bot.add_cog(cogs(bot))

@commands.Cog.listener()
async def on_ready(self):
    print("cogs.py is ready!")

@commands.command()
async def embed(self, ctx):
    embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)

    embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
    embed_message.set_thumbnail(ul=ctx.guild.icon)
    embed_message.set_image(url=ctx.guild.icon)
    embed_message.add_field(name="Field name", value="Feild value", inline=False)
    embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)

    await ctx.send(embed = embed_message)

async def setup(client):
await client.add_cog(cogs(client))

   ```
sick birch
#

See here for a simple example

#

With a callback

frosty parrot
#

it doesn't give me errors

#

but the bot doesn't responding to the commands

slate swan
#

@sick birch ```[2023-02-26 22:57:23] [INFO ] discord.client: logging in using static token
[2023-02-26 22:57:24] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 21523dba6f5793dfde7b181d93a927c6).
Logged in as Blinded Tickets#7696
[2023-02-26 22:57:28] [ERROR ] discord.ext.commands.bot: Ignoring exception in command new
Traceback (most recent call last):
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 32, in new
view.add_item(button.with_callback(button_callback))
AttributeError: 'Button' object has no attribute 'with_callback'

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

Traceback (most recent call last):
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Button' object has no attribute 'with_callback'

sick birch
#

Can you show your code?

slate swan
#

yes

frosty parrot
slate swan
sick birch
#

Did you read the example? This isn't how you register a callback

smoky sinew
#

button.with_callback??

compact stag
smoky sinew
#

@slate swan why don't you just use a class-based view instead???

#
class PurchaseTicketView(discord.ui.View):
    @discord.ui.button(label = "Open Ticket", style = discord.ButtonStyle.green, custom_id = "open_ticket")
    async def open_ticket(self, interaction, button):
        ...
slate swan
#

lets see

smoky sinew
#

then you do ```py
message = await ctx.send(
"my message",
embed = embed,
view = PurchaseTicketView()
)

#

also, why are you using both wait_for and a button?

#

don't they replace each other

slate swan
#

thats for inactivity.

#

"wait"

smoky sinew
#

???

slate swan
#

nvm

smoky sinew
#

yes, but if the user doesn't press the button it'll be inactive too

slate swan
#

but let me try ur code.

smoky sinew
#

right??

slate swan
#

not really.

#

kinda

#

@smoky sinew

smoky sinew
#

what's your code

slate swan
naive briar
slate swan
#

wdym

naive briar
#

Then switch the button and interaction position in the callback argument

smoky sinew
#

did you get any error

#

oh nvm

slate swan
# smoky sinew did you get any error
[2023-02-26 23:03:52] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 6a080f3c6f3c1f415eb57c801fa9e7e2).
Logged in as Blinded Tickets#7696
[2023-02-26 23:03:57] [ERROR   ] discord.ui.view: Ignoring exception in view <PurchaseTicketView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Open Ticket' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\xavie\OneDrive\Documents\kca.py", line 15, in open_ticket
    member = interaction.user
AttributeError: 'Button' object has no attribute 'user'
smoky sinew
#

do what cat lover said

#

but also the error literally tells you

slate swan
#

alr

#

@smoky sinew @naive briar ```Microsoft Windows [Version 10.0.19045.2604]
(c) Microsoft Corporation. All rights reserved.

C:\Users\xavie\OneDrive\Documents>kca.py
Traceback (most recent call last):
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 19, in <module>
bot.add_view(PurchaseTicketView())
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 190, in init
self.__stopped: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
RuntimeError: no running event loop

C:\Users\xavie\OneDrive\Documents>```

#

and ill send code

#

I think I have to add a run() method.

naive briar
#

Like setup_hook

smoky sinew
#

do it in setup_hook

#

but i'm not even sure where ur doing it rn

slate swan
#

my brain

#

hurts. where do I do setup_hook

smoky sinew
#

@slate swan if each user is going to run this command, then don't make the view persistent because it can use up a lot of resources

unkempt canyonBOT
#

Hey @mild geode!

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

slate swan
#

add_view?

smoky sinew
mild geode
smoky sinew
#

then replace commands.Bot with TicketBot when you create it

mild geode
#

but it doesnt respond to commands

#

can anyone help me?

naive briar
#

It's not a coroutine btw

smoky sinew
#

also @mild geode you shouldn't store user levels in a json file

mild geode
#

but when i do bot.command

#

i get error

#
Traceback (most recent call last):
  File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 64, in <module>
    @client.command(name=level)
AttributeError: 'Client' object has no attribute 'command'
smoky sinew
#

because you need to replace your client with a commands.bot

naive briar
#

Only discord.ext.commands.Bot has command extension

naive briar
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
smoky sinew
# mild geode ohk

you shouldn't mix on_message commands and commands extension together either

mild geode
#

hmm

#

can anyone help me how do i do this?

#

i did the logic behind the code

#

but im not good at discord

#

so yeah. any help?

#

like instruct me plz

#

can u just give me an example command?

#

ill do the rest

slate swan
#

@smoky sinew ```Microsoft Windows [Version 10.0.19045.2604]
(c) Microsoft Corporation. All rights reserved.

C:\Users\xavie\OneDrive\Documents>kca.py
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 51
await bot.setup()
^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function

C:\Users\xavie\OneDrive\Documents>```

#

im confused on this part.

naive briar
#

The error literally just told you

mild geode
smoky sinew
mild geode
#

just like hello world or smthing

smoky sinew
mild geode
smoky sinew
#
@bot.command()
async def command(ctx):
    await ctx.send("hello")
#

if you need a more complex example lmk

mild geode
#

bro not the command like the whole code like the import and everything

#

cuz you told to do some commands.bot

#

i didnt get that part

smoky sinew
#
bot = commands.Bot(
    command_prefix = "!",
    intents = # your intents here
)
#

?

mild geode
#

ok thanks

#

what should i import?

smoky sinew
#

from discord.ext import commands

hushed galleon
#

isnt the issue with their original code that they didnt enable the message content intent?

mild geode
smoky sinew
#

i mean maybe

#

but they didnt process commands either

mild geode
#
Traceback (most recent call last):
  File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 3, in <module>
    bot = commands.Bot(
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 171, in __init__
    super().__init__(intents=intents, **options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1302, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 253, in __init__
    self._connection: ConnectionState = self._get_state(intents=intents, **options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 284, in _get_state
    return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 221, in __init__
    raise TypeError(f'intents parameter must be Intent not {type(intents)!r}')
TypeError: intents parameter must be Intent not <class 'str'>
#
from discord.ext import commands

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

@bot.event()
async def on_ready():
    print(f"{bot.user} is online.")

@bot.command(name=hi)
async def hi(ctx):
    await ctx.send('LETS GO!')

bot.run('Invalid')
hushed galleon
#

you're meant to pass a discord.Intents object to the intents= parameter

mild geode
#

i have turned all these on

#

so what should the parameter be there?

smoky sinew
mild geode
#
from discord.ext import commands
import discord

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

@bot.event()
async def on_ready():
    print(f"{bot.user} is online.")

@bot.command(name=hi)
async def hi(ctx):
    await ctx.send('LETS GO!')

bot.run('MTA3OTAxNTExNjc0MzM4NTE4OA.G3Kh-0.YHhMpo38q')
#

code

#
Traceback (most recent call last):
  File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 5, in <module>
    intents = discord.Intents.all()
NameError: name 'discord' is not defined

C:\Users\user\OneDrive\Desktop\Coding\Nexus>python main.py
Traceback (most recent call last):
  File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 9, in <module>
    @bot.event()
TypeError: event() missing 1 required positional argument: 'coro'
#

error

#

im rly sry

smoky sinew
#

did you just send half a token lol

#

it's @bot.event not @bot.event()

mild geode
mild geode
smoky sinew
#

what extra steps do i need to take to shard my bot?

#

i know i should use AutoShardedBot instead of Bot but is there anything else?

frosty parrot
#

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.cog' raised an error: TypeError: cogs must derive from Cog

#

help!

#

anyone ?

shrewd apex
glass forge
#

does slash working? xD

shrewd fjord
#

Eh?

#

Wdym

naive briar
#

That's a familiar pfp

glass forge
#

i asking because i cant install slash dash module

naive briar
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
glass forge
#

πŸ€”

slate swan
#

I AM GETTING ERROR PLS FIX THIS Exception has occurred: TypeError BotBase.__init__() missing 1 required keyword-only argument: 'intents' File "C:\Users\badbo\Desktop\OwnedProjects\main.py", line 13, in <module> bot = commands.Bot(command_prefix='-',case_insensitive=True) TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

naive briar
#

Read the error

#

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

glass forge
glass forge
#

🀣

#

okay

shrewd fjord
#

Discord added slash commands on their new v2.0

#

Bro i am tripping πŸ’€

glass forge
#

im newbie

#

-_-

shrewd fjord
#

!intent

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.

shrewd fjord
#

Oh NVM

glass forge
#

!shashdash

#

-_-

#

root@sspanel:/home/bot# python3 bottesting.py
Traceback (most recent call last):
File "bottesting.py", line 2, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'

shrewd fjord
#

Dangggg

glass forge
#

πŸ™ƒ

shrewd fjord
#

;-;?

#

Ah danny bot isnt here

glass forge
naive briar
#

Don't say that it's chatgpt

shrewd fjord
#

Ash POG

glass forge
shrewd fjord
#

Ash on rescue

glass forge
frosty parrot
#

give me a full utility bot code

#

πŸ’€

glass forge
#

you me?

slate swan
#

why my bot code is getting this output instead of logging into bot -_-

#

pls fix this

#

my bot code```import discord
from discord.ext import commands
import logging
from pathlib import Path
import json
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

cwd = Path(file).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")

#bot secrets
secret_file = json.load(open(cwd+'/secrets.json'))
bot = commands.Bot(command_prefix="-",intents=intents, case_insensitive=True)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)

@bot.event
async def on_ready():
print(f"-----\nLogged in as : {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
#another way to use activity
print("-----\nLogged in as: {} : {}\n-----\nMy current prefix is: -\n-----".format(bot.user.name, bot.user.id))
await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to insteract with me!"))
#bot activity

@bot.command(name='hi', aliases=['hello'])
async def _hi(ctx):
"""
A simple command which says hi to the author
"""
await ctx.send(f"Hi {ctx.author.mention}!")

#edit command
@bot.command()
async def echo(ctx, *, message=None):
    """
    A Simple command that repeats the users input back to them
    """
    
    message = message or "please provide the message to be repeated"
    await ctx.message.delete()
    await ctx.send(message)
    
    bot.run(bot.config_token) ```
vocal snow
#

the bot.run is inside a command?

slate swan
#

umm yes

vocal snow
#

pithink why

slate swan
#

@vocal snowthnks buddy i got my fix

slate swan
glass forge
regal cove
#

how do i make a slash command admin only?

glass forge
#

@regal cove

regal cove
glass forge
#

perms for slash dash

glass forge
outer acorn
#

Looking now. Give me a sec

regal cove
#

what statement and or code do i need to make a command admin only?

glass forge
#

its easy system for perms in discord you can add for role and dont add to code

outer acorn
#

@glass forge Its just not sending the welcome and leave embed?

glass forge
#

yes

outer acorn
#

I'm running it rn on my server. Ill give you an answer in a sec

glass forge
#

oh okay

#
client.run("token")```
glass forge
#

m?

vale wing
unkempt canyonBOT
#

@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
vale wing
#

Probably this

shrewd fjord
#

Not probably, it is

glass forge
#

its not for me

shrewd fjord
#

Code?

glass forge
shrewd fjord
#

I said current code

#

Give the current code rn

vale wing
glass forge
#

for me

shrewd fjord
#

Mhm

glass forge
shrewd fjord
shrewd fjord
glass forge
shrewd fjord
#

Sorry nvm

vale wing
#

Sorry I am bad at reading

glass forge
#

ha

shrewd fjord
#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
shrewd fjord
#

@glass forge this ^^^

glass forge
shrewd fjord
#

Oh wait, my bad lol

glass forge
#

🀣 sorry

vale wing
#

Members intent required + does client even have those methods?

shrewd fjord
#

The web is not opening for me

#

Nvm opened

glass forge
#
async def on_member_join(self, member):
        guild = self.get_guild(796804050305417276) # Replace with your guild ID
        channel = guild.get_channel(1079697563848028180) # Replace with your channel ID

        # Create a welcome embed with a mention of the new member
        embed = discord.Embed(title=f"Welcome {member.mention}!", description="Hello and welcome to our server!")
        await channel.send(embed=embed)

    async def on_member_remove(member):
        guild = self.get_guild(796804050305417276) # Replace with your guild ID
        channel = guild.get_channel(1079697563848028180) # Replace with your channel ID

        # Create a goodbye embed with a mention to the leaving member
        embed = discord.Embed(title="Goodbye!", description=f"{member.mention} has left the server. Bye!")
        await channel.send(embed=embed)
shrewd fjord
unkempt canyonBOT
#

classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences"), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members"), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content").
glass forge
shrewd fjord
#

You need to enable "members" intents in code as well as in dev portal

#

!intent

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.

shrewd fjord
#

intents.members = True ^^^^

#

Or just simply do
discord.Intents.all() kek

glass forge
shrewd fjord
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
glass forge
#

read again

shrewd fjord
#

intents=discord.Intents.all()

glass forge
#

discord dont ban?

shadow wraith
#
@bot.slash_command()
async def where(inter, *, id):
    channel = bot.get_channel(1076863262613835828)
    messages = await channel.history().flatten()
    for index, element in enumerate(messages):
        print(index, element.reactions[index])
        async for user in element.reactions[index].users():
            if bot.get_user(id) == user:
                u = bot.get_user(id)
                inter.response.send_message(f"{u.name} is from {element.reactions[index].emoji}")
                break

using disnake
this hella confuses me, how do i get what the user reacted with in any message of a channel

glass forge
#
  File "bottesting.py", line 2
    class discord.Intents.all()
                 ^
SyntaxError: invalid syntax```
shrewd fjord
#

Did u try checking your own code?

#

There is a
super().init(...)

glass forge
shrewd fjord
#

Search it and lmk o
If u found it

glass forge
#

Fu##

shrewd fjord
#

?

glass forge
#

work

shrewd fjord
#

Realized? xd

glass forge
#

🀣

shrewd fjord
#

lol

glass forge
#

how remove prefix

unkempt mauve
#

Hello guys, I am using cogs. How do I sync my commands??

unkempt mauve
shrewd fjord
shrewd fjord
unkempt canyonBOT
#

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

Adds a β€œcog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
unkempt mauve
glass forge
#

πŸ₯²

shrewd fjord
unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
unkempt mauve
#

doesnt works with cogs πŸ’€

#

need to add client. while I am using bot

shrewd fjord
shrewd fjord
glass forge
#

its not work

slate swan
#

What

shadow wraith
unkempt mauve
shadow wraith
#

my brain is expldoing

shrewd fjord
#

Or just on start

unkempt mauve
#
@bot.event
async def on_ready():
    bot.loop.create_task(change_status())
    print("Bot is online!")```
shrewd fjord
#

await bot.add_cog(....)
await bot.tree.sync()

#

Simple

unkempt mauve
#

in the main() function?

shrewd fjord
shrewd fjord
unkempt mauve
#

yes

shrewd fjord
#

Extensions,
So better sync it on setup_hook

#

@bot.event
async def setup_hook()
await bot.tree.sync()
print("Yeah i synced commands and triggered setup_hook")

unkempt mauve
#

lol

#

okay

#

the print πŸ’€

shrewd fjord
#

πŸ’€πŸ’€πŸ’€

glass forge
#

πŸ§€

unkempt mauve
#

where tf all the commands went

shrewd fjord
#

πŸ’€πŸ’€πŸ’€πŸ’€

#

What did u do

unkempt mauve
#
async def main():
    for filename in os.listdir('./commands'):
      if filename.endswith('.py'):
        await bot.load_extension(f'commands.{filename[:-3]}')
        await bot.start("Bottoken")
discord.utils.setup_logging()

#setup hook
@bot.event
async def setup_hook():
    await bot.tree.sync()
    print("Synced all the commands!")
keep_alive()
asyncio.run(main())```
shrewd fjord
#

Wait f it's so weird

unkempt mauve
#

the whole?

shrewd fjord
unkempt mauve
#

my commands are vanished

#

you cant mention in title

#

move it to description

glass forge
#

a yes? sorry

shrewd fjord
#

Does it prints anything?

unkempt mauve
#

yes

#

"Synced all commands"

#

but never synced

shrewd fjord
#

try this... synced=await bot.tree.sync()
print(synced)

#

Maybe the bot doesn't have perms? Who knows

unkempt mauve
#

with bot applications enabled

#

I can see only one command

shrewd fjord
#

Hm pithink

shrewd fjord
#

app.commands scope enabled?

unkempt mauve
#

YES

#

it only synced one command!

#

I need to make a loop fr

shrewd fjord
#

Bro why loop lmao

unkempt mauve
shrewd fjord
#

Maybe u have only 1 slash cmd? πŸ’€

glass forge
#

who help me, very thanks

shrewd fjord
#

Nice

unkempt mauve
shrewd fjord
#

U said u r using cog no?

glass forge
#

how get budget?))

unkempt mauve
#

BRO ITS RANDOMLY SYNCING COMMANDS

#

it now synced help cmd

#

only help cmd now

shrewd fjord
#

Wait πŸ‘€

#

Ig try
to sync it on setup

shrewd fjord
unkempt mauve
shrewd fjord
slate swan
#

Also what’s the issue

unkempt mauve
shrewd fjord
#

Nothing

slate swan
unkempt mauve
slate swan
#

Oh lol

glass forge
#

----------______________________--------------

lyric sphinx
# glass forge how get budget?))

Have your own discord bot that supports slash commands in a community server (also have atleast 1 of the commands used in last month (iirc))

zealous yarrow
#
@bot.command()
async def google(ctx,arg):
    var_content = []
    var_header = []
    # Searching Google For Top Links
    var_searchQuery = str(arg)
    var_results = search(var_searchQuery , tld = "co.in" ,num = 3 ,stop = 3 , pause = 2)
    var_links = []
    for result in var_results :
        var_links.append(result)
    else :
        print("links found")
    
    # Fetching Data from Websites
    
    for link in var_links :
        var_rawData = req.get(link)
        var_htmlData = var_rawData.content
        var_soup = bs(var_htmlData , "html.parser")
        var_tempHeader = var_soup.find("title")
        var_tempContent = var_soup.find("p")
        var_content = var_content.append(var_tempContent.text)
        var_header = var_header.append(var_tempHeader.text)
        await ctx.send("Fetching Results...")
    else:
        print("started making embed")
        var_resultsEmbed = discord.Embed(title = f"Search Results For `{arg}`", color = 0x00ff00,
                                         url= "https://google.com")
        var_resultsEmbed.add_field(name=f"{var_header[0]}",value=f"{var_content[0]}",inline = False)
        var_resultsEmbed.add_field(name=f"{var_header[1]}",value=f"{var_content[1]}",inline = False)
        var_resultsEmbed.add_field(name=f"{var_header[2]}",value=f"{var_content[2]}",inline = False)
        
        await ctx.send(embed=var_resultsEmbed)
#

any idea why is this not working

#

no errors

#

it just stops after one iteration

#

the for loop

lyric sphinx
#

why are you doing var_content = var_content.append()?

#

append doesnt return, it adds inplace. You just need var_content.append()

zealous yarrow
#

it's to make the list of all the results

lyric sphinx
#

no?

#

append doesnt return

#

!e

x = []
x = x.append(10)
print(x)
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

None
lyric sphinx
#

!e

x = []
x.append(10)
print(x)
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

[10]
zealous yarrow
#

oh

#

oops

#

i just mixed two things in my head

lyric sphinx
#

also whats the point of naming every variable var_<name> lmao

shrewd fjord
#

Why else: is after for loop statement?

zealous yarrow
lyric sphinx
zealous yarrow
#
[2023-02-27 18:04:04] [WARNING ] discord.gateway: Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
shrewd fjord
#

Oh wait nvm

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!

zealous yarrow
#

mhm

#

but how do i change this uh

shrewd fjord
#

Use
aiohttp

#

Instead of requests

zealous yarrow
#

😫

#

does that work similar

lyric sphinx
#

yes

zealous yarrow
#

like just replce requests rest of the things like b4s will be same right ?

glass forge
#

πŸ₯² who can help me to write bot

#

i will give skin csgo)

shrewd fjord
#

Just,
async with aiohttp.ClientSession() as ses:
var_rawData=await ses.get("url")

zealous yarrow
#

what bot

shrewd fjord
lyric sphinx
#

!rule paid

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

zealous yarrow
#

L

unkempt mauve
#

how do I make the subcommands work

shrewd fjord
#

Slash sub cmds?

unkempt mauve
#

is there any problem with my slash cmds?

glass forge
shrewd fjord
#

Maybe ur sub cmds are wrong?

unkempt mauve
#

can I show u one of the codes?

shrewd fjord
#

Sec

shrewd fjord
#

Mind searching in google "discord.py app_commands walk through" there is all types.of slash commands with cog and without cog

unkempt mauve
lyric sphinx
#

It doesnt even have anything related to sub commands in your code

#

thats just a slash command

unkempt mauve
#

how do I make a parent cmd

lyric sphinx
#

subcommand of what?

unkempt mauve
shrewd fjord
#

I cant search rn, that's why gave u

#

Oh f, need to check docs

#

Docs*, there is something similar to this

unkempt mauve
shrewd fjord
#

Bro fr there is something like this lmao

#

I just forgot

unkempt mauve
#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
plain hazel
#

hellow, does anyone is currently developping a bot with python 3.11.2 and VScode ?

shrewd fjord
#

apgg

lyric sphinx
#

!d discord.ext.commands.Bot.hybrid_group

shrewd fjord
#

U found it xd

unkempt canyonBOT
#

@hybrid_group(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_group "discord.ext.commands.hybrid_group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
shrewd fjord
#

Not hybrid πŸ’€πŸ’€

austere prairie
unkempt mauve
#

who is going to use hybrid bru

#

app_commands.Group

plain hazel
shrewd fjord
#

Lol

austere prairie
#

Are you getting an error?

plain hazel
#

what version do you recommand to me

shrewd fjord
#

3.10

austere prairie
#

^

plain hazel
#

yeah i tried everything

shrewd fjord
#

Python version

plain hazel
#

so 3.10

#

can i still do everything

shrewd fjord
#

Tho python 3.11 wont give much problems

austere prairie
#

dpy is pure python, so it should work just fine in 3.11 anyway

shrewd fjord
#

Yep

#

Sarth online POG

plain hazel
#

so my error doesn't come from the py version

austere prairie
#

Are you getting 'missing required argument intents'?

slate swan
austere prairie
#

Ah ic, good to know

plain hazel
#

i deleted everything to do it properly with yall advices x)

#

wasn't able to start a thing anyway

zealous yarrow
#

hi uh

#
@bot.command()
async def google(ctx,arg):
    var_content = []
    var_header = []
    # Searching Google For Top Links
    var_searchQuery = str(arg)
    var_results = search(var_searchQuery , tld = "co.in" ,num = 3 ,stop = 3 , pause = 2)
    var_links = []
    for result in var_results :
        var_links.append(result)
    else :
        print("links found")
    
    # Fetching Data from Websites
    
    for link in var_links :
        async with aiohttp.ClientSession() as ses:
            var_rawData=await ses.get(link) 
            var_htmlData = var_rawData.content
            var_soup = bs(var_htmlData , "html.parser")
            var_tempHeader = var_soup.find("title")
            var_tempContent = var_soup.find("p")
            var_content.append(var_tempContent.text)
            var_header.append(var_tempHeader.text)
            await ctx.send("Fetching Results...")
    else:
        print("started making embed")
        var_resultsEmbed = discord.Embed(title = f"Search Results For `{arg}`", color = 0x00ff00,
                                         url= "https://google.com")
        var_resultsEmbed.add_field(name=f"{var_header[0]}",value=f"{var_content[0]}",inline = False)
        var_resultsEmbed.add_field(name=f"{var_header[1]}",value=f"{var_content[1]}",inline = False)
        var_resultsEmbed.add_field(name=f"{var_header[2]}",value=f"{var_content[2]}",inline = False)
        
        await ctx.send(embed=var_resultsEmbed)
#

still not working

#

like idk if the loop is even iterating

#

it didn't send even one response

#

@lyric sphinx

#

it's not fetching data

#

i checked

unkempt canyonBOT
#

Hey @mild geode!

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

mild geode
mild geode
#

Anybody can help me here?

lyric sphinx
#

you really shouldnt use a plaintext for this

#

thats a great opportunity to learn databases :d

mild geode
#

which one do you suggest? although i just want in plain text tbh

lyric sphinx
#

SQLite is probally the easiest to use

mild geode
#

Hmm okay

#

thanks

zealous yarrow
#

how about i try making it as an external function and just call that function in the bot command

lyric sphinx
#

shouldnt it be something like

async with session.get("link") as r:
zealous yarrow
#

will it work thinkmon

#

cuz when i was doing this outside of the bot code

#

it just worked

#

it worked good there

lyric sphinx
#

well, because it didnt have to do any async stuff

#

the actual code was fine for a standalone command, but not for a bot

zealous yarrow
#

so it will be the same even if i make it as an external function

#

and call it under the async

plain hazel
#

does anyone have a clue about that ?

naive briar
#

What are you trying to do

plain hazel
naive briar
#

Let me guess, YouTube?

#

Exit the repl then type pip --help

plain hazel
#

yeah sadly i'm not getting nice stackoverflow resources

#

yeah pip work outside python

#

but why does it work inside for him uhh

naive briar
#

It's meant to be use in the terminal/console/whatever

plain hazel
#

okay thanks

#

also it suggest me to upgrade it to 23.0.1, shoud I ?

naive briar
#

Upgrade what

#

Pip?

plain hazel
#

yeah

hushed galleon
#

i think thats the onboarding community feature

slate swan
#

ohhhh

hushed galleon
slate swan
#

yup thats it

#

ty!

thin raft
#

when should I change presence?

drifting arrow
#

So question, how does a bot like Mee6 handle being in like 20+million servers?

fallow mauve
#

Can someone give me reasons why not to use replit? Everyone has told me that it sucks but I can't see why lol. If you can suggest some other code editor that's free and can run in the browser then great but right now I don't see replit as being an issue.

fallow mauve
#

or have a mobile app

drifting arrow
#

oh

fallow mauve
#

yeah my issue is i cant install software on pc bcs i dont own the pc

hushed galleon
vocal wraith
#

Hi I watched a video on how to make a discord bot but when I run it it just says this
`Traceback (most recent call last):
File "E:\PyCharm Projects\Teki-Key Bot\main.py", line 4, in <module>
bot.run_discord_bot()
File "E:\PyCharm Projects\Teki-Key Bot\bot.py", line 15, in run_discord_bot
client = discord.Client()
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'

Process finished with exit code 1`

hushed galleon
#

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

hushed galleon
#

the tutorial you're watching is likely outdated by now since discord.py 2.0 got released six months ago

vocal wraith
#

It says uh let me look

#

oh yeah 6 months

#

So can someone help since I'm new#

slate swan
# thin raft when should I change presence?

if it has to be the same throughout the session you can do it using status and activity kwarg inside the bot constructor, else you can do it anywhere after the bot is connected to websocket and all the READY and initial GUILD_CREATE events have been processed ( which discord.py looks after with the Client.wait_until_ready() lock

hushed galleon
#

see the tag:

Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
and the code snippet inside demonstrates how you would define your intents and pass it as an argument to your bot constructor

vocal wraith
#

I'm new still so im really stuck

fallow mauve
vocal wraith
hushed galleon
#

!e py def my_function(*, intents): ... this is a function, and in this case the parameter intents is 1: required, and 2: keyword-only, so when you call the function it must be done like this: py my_function(intents="hello world!") if you don't pass said argument and just call the function without any arguments: py my_function() you get the same error you saw before:

unkempt canyonBOT
#

@hushed galleon :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | TypeError: my_function() missing 1 required keyword-only argument: 'intents'
hushed galleon
#

the prior tag explains why intents matter to your discord bot, how to enable privileged intents in the discord developer portal like message_content, and how to specify the intents you want your bot to use when its connecting to discord

white citrus
#
class NewWarnModal(nc.ui.Modal):
    def __init__(self, target):
        self.target = target
        super().__init__(f"Warning for {self.target}")
        
        
        
        self.reason = nc.ui.TextInput(label="Reason", style=nc.TextInputStyle.paragraph, placeholder="Type here your reason", required=True, max_length=50)

        self.add_item(self.reason)


    async def callback(self, inter: nc.Interaction):
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                
                random_id = generate_random_id(10)
                user_dm = nc.Embed(title=f"You are beeing warned on {inter.guild.name}",
                                   description=f"__**Reason:**__\n{self.reason}")
                user_dm.set_footer(text=f"Warned by: {inter.user}", icon_url=inter.user.avatar.url)
                current_time = int(time.time())
                await cursor.execute('INSERT INTO warn_system (guild_id, user_id, warned_by, date, reason, case_id) VALUES (?, ?, ?, ?, ?, ?)',
                                     (inter.guild.id, self.target.id, inter.user.id, current_time, self.reason.value, random_id,))
                await inter.response.send_message(content="sucess")``` 
The Insert wont work
#

No error

#

He sends sucess

vocal wraith
#

This is what happens to me

hushed galleon
shrewd fjord
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.

vocal wraith
#

Where do I put that

shrewd fjord
#

put it on your bot instance

vocal wraith
shrewd fjord
#

If u using class
put it inside ....
super().init(....)

hushed galleon
fallow mauve
#

i need someone to help me. i havent coded in months and i may have forgotten a lot and ik stuff is outdated lmao

hushed galleon
fallow mauve
vocal wraith
hushed galleon
#

depends on how they named their script

vocal wraith
#

its outdated now

fallow mauve
#

make sure that youre watching an up to date tutorial

vocal wraith
#

@hushed galleon can you help me rewrite in dms

white citrus
vague gulch
#

Can someone make me a bot for my server?

fallow mauve
vague gulch
#

The stuff mee6 can do but I don't like mee6 cuz of all the trouble that is going on with it

fallow mauve
#

uh yeah i cant do that much sry, try bots like dyno tbh

vague gulch
#

I have dyno

#

But ots limited to what it can do

fallow mauve
#

dm me i can help

vague gulch
#

Ok

radiant bough
#

How do I get a channel inside the button class?

#

self.bot.get_channel(...)?

slate swan
#

interaction.client.get_channel

radiant bough
#

client?

slate swan
#

!d discord.Interaction.client this

unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
slate swan
#

attribute error : 'bot' has no attribute 'logout'

#

pls tell me how to fix this

radiant bough
analog wave
#

Given a string S check if is a valid email id based on the following Conditions
1)@ should be present;
2)@ & . should not be repeated;
3)there should be atleast four characters between @ and .;
4)there should be at-least 3 characters before @ ;
5)the end of mail id should be .com; If its a valid email id print 'YES' else print 'NO'.
input size : |S|<=100000
example
INPUT
test@gmail.com
OUTPUT
YES

#

need help

#

email_re = re.compile(r'^[a-z_-]{3}+@[a-z]{3}+.[a-z]{3}$')
user_email_id = input("enter your id 😊
if re.search(email_re, user_email_id):
print("right email")
else:
print("invalid email")

#

code i have written showing incorrect

white citrus
#
class SelectEditWarn(nc.ui.Select):
    def __init__(self, target):
        
        self.target = target
        
        async def get_options(self):
            async with aiosqlite.connect("maja.db") as db:
                async with db.cursor() as cursor:
                    await cursor.execute('SELECT case_id FROM warning_system WHERE user_id, guild_id = ?, ?', (self.target.id, nc.Interaction.guild.id,))
                    case = await cursor.fetchall()
                    return case

                            
        for option in get_options:
            
            async def get_reason(self):
                async with aiosqlite.connect("maja.db") as db:
                    async with db.cursor() as cursor:
                        await cursor.execute('SELECT reason FROM warning_system WHERE case_id, guild_id = ?, ?', (option, nc.Interaction.guild.id,))
                        reason = await cursor.fetchone()
                        new_option = nc.SelectOption(label=option, description=reason[0])
            
        super().__init__(placeholder="Choose a chase", min_values=1, max_values=1, options=#I can't get any further here)```
#

The idea is to get all warnings from the member and then list them in a select menu so you can look for a case

radiant bough
#
await interaction.client.load_extension(. . .)
``` would work?
radiant bough
#

no

#

Mb I forgot to reply

#

Btw how do I get the reason for ban in on_member_ban event?

frosty parrot
#
import asyncio
from random import random
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle


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


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

bot_status = cycle(["Watchig everyone", "Moderating", "banning a person"])

@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(activity=discord.Game(next(bot_status)))

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print("Success: The bot is connected to discord")
    change_status.start()


#commands list

@client.command()
async def hello(ctx):
    await ctx.send("Hi. How's going ? It's good to here from you.")

@client.command()
async def ping(ctx):
    await ctx.author.send("Pong!")

async def load():
    for filename in os.listdir("discrdbot\cogs"):
        if filename.endswith(".py"):
            await client.load_extension(f"cogs.{filename[:-3]}")
            print(f"{filename[:-3]} is loaded!")

async def main():
    async with client:
        await load()
        await client.start("MY BOT TOKEN")

asyncio.run(main())```
#

the main code

#
from discord.ext import commands

class cogs(commands.Bot):
    def __init__(self, client):
        self.client = client

class Greetings(commands.Cog):
    def __init__(self, client):
        self.client = client
        self._last_member = None
    
    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = member.guild.system_channel
        if channel is not None:
            await channel.send(f'Welcome {member.mention}.')

    @commands.command()
    async def hello(self, ctx, *, member: discord.Member = None):
        """Says hello"""
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send(f'Hello {member.name}~')
        else:
            await ctx.send(f'Hello {member.name}... This feels familiar.')
        self._last_member = member
    
    def setup(bot):
        bot.add_cog(cogs(bot))
    
    @commands.Cog.listener()
    async def on_ready(self):
        print("cogs.py is ready!")

@commands.command()
async def embed(self, ctx):
    embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)

    embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
    embed_message.set_thumbnail(ul=ctx.guild.icon)
    embed_message.set_image(url=ctx.guild.icon)
    embed_message.add_field(name="Field name", value="Feild value", inline=False)
    embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)

    await ctx.send(embed = embed_message)
    
async def setup(client):
    await client.add_cog(cogs(client))```
#

the cog

#
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: TypeError: cogs must derive from Cog```
#

the error

#

what's the problem ?

quick gust
frosty parrot
#

What

hushed galleon
#

extensions dont typically need to define a subclass of commands.Bot

vocal wraith
#

can you help me remake discord bot

hushed galleon
#

in your case you probably meant to construct an instance of the Greetings cog

frosty parrot
#

Can you write me a discord bot code ? πŸ’€

vocal wraith
#

i didnt ask that

#

i said i needed help remaking

frosty parrot
vocal wraith
#

ohk

hushed galleon
vocal wraith
#

Okay cheers

radiant bough
fallow mauve
frosty parrot
#

Bro that's happening with me too

#

But the tutorial is 5 months old

#

And still giving me errors

sick birch
#

Discord.py changes very frequently, especially the past few months. I wouldn't recommend any tutorial a month or 2 old

#

Heck, I don't recommend tutorials for discord.py in general

frosty parrot
#

Why

sick birch
frosty parrot
#

Then suggest me a terrible

#

πŸ’€

sick birch
#

Pardon?

frosty parrot
#

Yep

sick birch
#

... I- I'm not following

frosty parrot
#

😭

vague gulch
#

Can someone make me a bot like sounds?

thin raft
#

no

fallow mauve
fallow mauve
slate swan
#

Traceback (most recent call last):
File "main.py", line 4, in <module>
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ModuleNotFoundError: No module named 'discord_components'
ξΊ§

#

can somebody help me out with this?

shrewd apex
#

or wait a little longer for discord to deprecate that api version emoji_3

glass forge
#

im try create custome voice

async def on_voice_state_update(member, before, after):
    if before.channel is None and after.channel is not None and after.channel.id == 1070962969904680970: # Replace with the ID of the source voice channel
        # Get the target voice channel by ID
        target_channel = bot.get_channel(1079874258668367933) # Replace with the ID of the target voice channel
        # Create a new custom voice channel with a unique name
        new_channel = await target_channel.category.create_voice_channel(name=f"Custom Voice Channel - {member.display_name}")
        # Move the member to the new channel and give them permissions to edit the channel
        await member.move_to(new_channel, reason="Moved to a custom voice channel", permissions=discord.Permissions(voice=True, manage_channels=True))
``` its correct?
slate swan
#
async def clear(ctx, limit: int = None):
    with open("access.txt") as f:
        if str(ctx.guild.id) not in f.read():
            if limit == None:
                await ctx.channel.purge(limit=30)
                await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
            else:
                if limit > 30:
                    await ctx.send("[**ERROR**] Your max limit is 30.")
                else:
                    await ctx.channel.purge(limit=limit)
                    await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
        elif str(ctx.guild.id) in f.read():
            if limit == None:
                await ctx.channel.purge(limit=10000)
                await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
            else:
                await ctx.channel.purge(limit=limit)
                await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt work?
sick birch
#

Could you mind elaborating a bit more? I'm not sure I'm following what you mean by "field"

sick birch
#

Ah, I see what you mean. The before and after objects of certain events gives you the entire new state of the objects, rather than just the incremental changes

#

It's up to you to parse out which is new and which is old information, unfortunately

#

Well.. an embed "field" can have one title and one value

#

When you look at it that way, it does make sense why you can't "append" to a value

#

That would imply you can have more than one value

#

(which you don't)

glass forge
sick birch
#

I'm guessing by "adding values to an embed field" you mean adding a new "line" seperated by \n

#

Which is still just "one value"

#

I hope that perspective explains why you can't "append to a value"

#

... However it does have a pretty simple "fix"

#

You'd create some variable that stores the value of the field, append to the variable, then you'd update the embed and pass in the variable as the value

#

So:

my_var = "This is line 1"
my_embed = discord.Embed(...)
my_embed.add_field(..., value=my_var)
# you can now "update" the field:
my_var += "\nThis is line 2!"
# Edit the view, resend it
#

The idea is to not directly edit the Embed, but to edit it via a "proxy" of sorts, if that makes sense

smoky sinew
smoky sinew
#

@glass forge

smoky sinew
#

anyone know what property is used to check the invite the user joined from

#

or is it just detected by seeing which invite goes up in uses when someone joins?

slate swan
#

yep the discord API doesn't provide any way to figure that out explicitly

#

you'll have to see the invite logs

smoky sinew
unkempt mauve
#

how do I check the interaction user's permission? got it

sick birch
#

Compare the invite logs before and after, check for the delta

frosty parrot
#

discord.ext.commands.errors.MissingRequiredArgument: guess is a required argument that is missing

#

what to do ?

naive briar
#

Give it enough arguments

frosty parrot
#

I don't know about coding that's why I'm asking bro tell me what to do

quick gust
#

step 1: you dont copy code which u don't understand

smoky sinew
#

what delta??

smoky sinew
#

read what it says

frosty parrot
sick birch
#

You know which invite was used by figuring out which count went up by 1

#

It's frankly a major PITA

smoky sinew
#

yeah that's what i suggested

#

i want to create a lobste.rs type invite tree command

unkempt mauve
#

How do I set a description for an argument?

smoky sinew
unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
unkempt mauve
#

thank you

smoky sinew
unkempt mauve
#

how do I add the mention thing in the argument

smoky sinew
#

?

unkempt mauve
#

in slash cmds

smoky sinew
#

i don't know what you mean

#

you can annotate it as discord.Member to set the type

unkempt mauve
unkempt mauve
#

thanks

frosty parrot
#
async def hello(ctx):
    with open("discrdbot/random.txt", "r") as f:
        random_responses = f.readlines()
        response = random.choice(random_responses)
    
    await ctx.send(response)```
#
'choice'```
unkempt mauve
#

How do I send the direct message to the user when the user is banned?

frosty parrot
#

help me ! tell me what to do

naive briar
#

!d discord.Member.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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
frosty parrot
#

good question

#

tell be bro, I don't want that my bot giving me the same greetings all the time

flat pier
#

i would hope random is the builtin random module

frosty parrot
#

yea

#

but I don't know what to do

slate swan
#

Can u show what is random

naive briar
slate swan
#

Also

#

Dont name files name as modules

frosty parrot
#

I named that responses

#

oh shit no

slate swan
#

..

frosty parrot
#

let me check

slate swan
#

sure

smoky sinew
frosty parrot
#

I just read the docs but still did the same

smoky sinew
#

πŸ’€

slate swan
frosty parrot
#
'choice'```
#

same error

flat pier
#

can you send the full traceback instead

slate swan
#

yes

flat pier
#

and possibly your full code

slate swan
calm sapphire
#

is there a afk json database code?

flat pier
naive briar
#

JSON isn't a database

frosty parrot
#

this check bro

slate swan
calm sapphire
slate swan
calm sapphire
frosty parrot
slate swan
#

Nice

calm sapphire
#

where do i find full codes

slate swan
calm sapphire
flat pier
frosty parrot
#
from random import random, choice
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle


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


bot = commands.Bot(command_prefix='=', intents=intents)

bot_status = cycle(["Watchig everyone", "Moderating", "banning a person"])

@tasks.loop(seconds=10)
async def change_status():
    await bot.change_presence(activity=discord.Game(next(bot_status)))

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print("Success: The bot is connected to discord")
    change_status.start()


#commands list



@bot.command()
async def ping(ctx):
    await ctx.send("Check your Dms'.")
    await ctx.author.send("Pong!")

@bot.command()
async def hello(ctx):
    with open("discrdbot/responses.txt", "r") as f:
        random_responses = f.readlines()
        response = random.choice(random_responses)
    
    await ctx.send(response)

bot.run("bot token")```
frosty parrot
#

hmm

flat pier
#

why are you import random from random

slate swan
#

Bruh

flat pier
#

you should be using choice directly since you imported that from random

#

and not importing random from random either

frosty parrot
slate swan
#

wdym

frosty parrot
slate swan
frosty parrot
slate swan
#

Yeah got it

flat pier
#

either way, its wrong

its also not recommended to use on_ready for anything that can make an API requests, along with using urllib since its blocking πŸ•Ί

slate swan
#

That u didn’t imported

frosty parrot
#

should I use from random import choice ?

naive briar
#

!e

import random
print(random.choice(range(10)))
unkempt canyonBOT
#

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

9
naive briar
#

Just import it normally 🀨

frosty parrot
#

ok

flat pier
frosty parrot
#

let me check

smoky sinew
#

good luck with that

calm sapphire
#

?

#

bruv iv made a discord bot with 427 commands

smoky sinew
#

yeah and you said you copied and pasted all of it from tutorials

slate swan
frosty parrot
slate swan
#

The index ur trying to access isnt there

brazen raft
frosty parrot
flat pier
brazen raft
slate swan
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: list index out of range
stoic apex
#
@bot.tree.command(name="equip")
@app_commands.describe(tests="test")
@app_commands.choices(choices=[
    app_commands.Choice(name="country", value="country"),
    app_commands.Choice(name="planet", value="planet"),
    ])
async def rps(i: discord.Interaction, choices: app_commands.Choice[str], tests:str):    
    if (choices.value == "country"):
        Whatever[i.user.id] = "country"
    elif (choices.value == 'planet'):
        Whatever[i.user.id] = "planet" 
@rps.autocomplete("tests")
async def choice(ctx,choice:str):
    d = []
    if Whatever[ctx.user.id] == "country":
        for c in ["country1","test2","test3",
                "test4","test5","test6"
                ]:
            if choice.lower() in c.lower():
                d.append(app_commands.Choice(name=c, value=c))
    if Whatever[ctx.user.id] == "planet":
        for c in ["planet","test2","test3",
                "test4","test5","test6"
                ]:
            if choice.lower() in c.lower():
                d.append(app_commands.Choice(name=c, value=c))
    return d
naive briar
#

Only if people actually read the errors

frosty parrot
smoky sinew
#

choices are handled for you i'm pretty sure but you need to annotate it as Choice

brazen raft
naive briar
#

For it to work properly on Windows

brazen raft
#

For what to work

#

The library works flawlessly on Windows

frosty parrot
#

oh I forgot to delete that I was using another code thats why

brazen raft
#

Can you paste your code now so I know why you got that last error?

naive briar
#

🀷

frosty parrot
brazen raft
#

Yes

frosty parrot
#

wait for a little while I'm sending my full code

stoic apex
frosty parrot
#
import random
print(random.choice(range(10)))
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle

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

bot = commands.Bot(command_prefix='=', intents=intents)

bot_status = cycle(["Watchig everyone", "Clash of Clans",])

@tasks.loop(seconds=10)
async def change_status():
    await bot.change_presence(activity=discord.Game(next(bot_status)))

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print("Success: The bot is connected to discord")
    change_status.start()```
#
async def ping(ctx):
    await ctx.send("Check your Dms'.")
    await ctx.author.send("Pong!")

@bot.command()
async def hello(ctx):
    with open("discrdbot/responses.txt", "r") as f:
        random_responses = f.readlines()
        response = random.choice(random_responses)
    
    await ctx.send(response)

class Greetings(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
    
    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = member.guild.system_channel
        if channel is not None:
            await channel.send(f'Welcome {member.mention}.')

    @commands.command()
    async def hello(self, ctx, *, member: discord.Member = None):
        """Says hello"""
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send(f'Hello {member.name}~')
        else:
            await ctx.send(f'Hello {member.name}... This feels familiar.')
        self._last_member = member```
brazen raft
frosty parrot
#
async def embed(self, ctx):
    embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)

    embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
    embed_message.set_thumbnail(ul=ctx.guild.icon)
    embed_message.set_image(url=ctx.guild.icon)
    embed_message.add_field(name="Field name", value="Feild value", inline=False)
    embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)

    await ctx.send(embed = embed_message)

@bot.command()
async def userinfo(ctx, member: discord.Member=None):
    if member is None:
        member = ctx.author
    elif member is not None:
        member = member

    info_embed = discord.Embed(title=f"{member.name}'s User Information", discription="All information about this user.", color=member.color)
    info_embed.set_thumbnail(url=member.avatar)
    info_embed.add_field(name="Name", value=member.name, inline=False)
    info_embed.add_field(name="Nick Name", value=member.display_name, inline=False)
    info_embed.add_field(name="Discriminator", value=member.discriminator, inline=False)
    info_embed.add_field(name="ID", value=member.id, inline=False)
    info_embed.add_field(name="Top Role", value=member.top_role, inline=False)
    info_embed.add_field(name="Status", value=member.status, inline=False)
    info_embed.add_field(name="Bot User", value=member.bot, inline=False)
    info_embed.add_field(name="Creation Date", value=member.created_at.__format__("%A, %d. %B %Y @ %H:%M:%S"), inline=False)

    await ctx.send(embed=info_embed)
    


bot.run("bot token")```
#

main filethis

#
Hello
How are you doing
How can I help you```responses.txt
frosty parrot
#

just tell me what to do or I cant understand

#

πŸ’€

brazen raft
#

I can see points of improvement

#

But I don't see anything that would raise an IndexError

#

Are you still getting it?

frosty parrot
#

when I'm sending the command

brazen raft
#

Can you locate the line

frosty parrot
#

but normally it's working

brazen raft
#

In the error traceback

frosty parrot
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range

brazen raft
#

Alright but what line does it say that it did that?

frosty parrot
#

last

#

after getting this the bot still working

brazen raft
#

What line of code does the error traceback says raised the exception

frosty parrot
brazen raft
#

What's the above exception? It says

The above exception was the direct cause of the following exception:
frosty parrot
#

then what to do now ?

brazen raft
#

You can send the entire traceback you're getting as a text file or something

frosty parrot
#

can you write me that ?

#

I can't

vocal snow
#

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

vocal snow
#

Send the full traceback in this

frosty parrot
#

ok

#

how to share this ?

#

sending the link ?

brazen raft
#

Ye

frosty parrot
vocal snow
frosty parrot
#

oh shit no

vocal snow
#

We need to see it to know what's going wrong πŸ˜…

frosty parrot
#

yep

brazen raft
#

f.readlines() must be returning an empty list

#

random.choice raises that exception on an empty collection, I've just tested

frosty parrot
#

this is the responses.txt file

brazen raft
frosty parrot
brazen raft
#

Frankly I think you would get an OSError for trying to open a non existent path in reading mode, so the path should be accessible to the script

#

Have you tried saving responses.txt

frosty parrot
#

if I don't use the responses.txt then ?

brazen raft
#

It was probably empty before you edited it and forgot to save

frosty parrot
#

bro

#

It was not saved

brazen raft
#

And your Greetings cog won't load itself. Also it has its own hello command which would conflict with the cogless hello command we're working on

frosty parrot
#

then I have to delete the command right ? or change the greetings ?

brazen raft
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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

Adds a β€œcog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
brazen raft
#

Normally you'd have something like this in your setup_hook override:

async def setup_hook(self):
    # for every cog
    self.add_cog(Cog(self))
naive briar
#

add_cog is a coroutine, so await it

brazen raft
frosty parrot
#

my ping.py isn't loading so I didn't load that

#

I have more commands in that file

brazen raft
frosty parrot
#

bro you are right πŸ˜‚

#

it wasn't saved πŸ€“

frosty parrot
#

I changed the hello command to hi

#

It'll be work now right ? the greetings

brazen raft
#

If it's loaded, sure. It shouldn't conflict then

smoky sinew
#

hi

drifting arrow
#

How would I setup my discordbot so it detects whenever it joins a new discord server?

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
drifting arrow
#

Neat

#

Ty @slate swan

slate swan
#

No problem

drifting arrow
#

Can I make my discordbot automatically leave a server as well?

brazen raft
#

Leave when

naive briar
#

!d discord.Guild.leave

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
frosty parrot
#

now what is it ?cycle expected 1 argument, got 2

quick gust
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

frosty parrot
#

@tasks.loop(seconds=10)
async def change_status():
    await bot.change_presence(activity=discord.Game(next(bot_status)))```
unkempt canyonBOT
#

itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:

```py
def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
```...
brazen raft
frosty parrot
#

but it was working fine

naive briar
#

And it now is?

frosty parrot
#

yes

brazen raft
#

It had brackets so it was in a list

#

I have no idea why the brackets are gone now

frosty parrot
brazen raft
#

They are the one and only pair of brackets on that line

frosty parrot
#

I removed them I thought it's useless

#

oh it's working now

brazen raft
#

The pair of brackets makes it a list (which itertools.cycle accepts). Without the brackets you would be sending it multiple arguments which itetools.cycle doesn't accept. The trailing comma before the closing bracket is useless

glass forge
frosty parrot
brazen raft
#

Why after a month

#

I mean the month ends soon anyway πŸ€”

frosty parrot
brazen raft
#

Good luck

frosty parrot
#

thanks

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'discription'

#

what is it ?

#

I used userinfo command

brazen raft
#

description not discription

frosty parrot
#

shit

#

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

#

this one ?

unkempt canyonBOT
#

Hey @spice zenith!

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

spice zenith
#

Traceback (most recent call last):
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\jaime\PycharmProjects\BOT\EX BOT\main.py", line 1595, in shop
d.execute("""
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

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

Traceback (most recent call last):
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'shop' raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported type.

#

im getting this error in that code and idk why^^'

#

can anyone help me pls

dull terrace
#

have there been any updates to discord in terms of components? anything new aside from selects, buttons and the pop out forms

dull terrace
frosty parrot
#

hey @brazen raft

dull terrace
spice zenith
#
c.execute("""CREATE TABLE IF NOT EXISTS games (

                     member_id INTEGER UNIQUE,
                     character TEXT,
                     level INTEGER,
                     wins INTEGER,
                     money INTEGER,
                     attack_1 TEXT,
                     level_1 INTEGER,
                     attack_2 TEXT,
                     level_2 INTEGER,
                     attack_3 TEXT,
                     level_3 INTEGER,
                     attack_4 TEXT,
                     level_4 INTEGER,
                     miximax TEXT ,
                     eg TEXT, 
                     tactic TEXT,
                     stadium TEXT
                     )""")```
dull terrace
#

okay and which column are you trying to input 1

spice zenith
#

first one is money

#

second one is miximax

#
money=int(50000)
                miximax=str('Unlocked')
                d.execute("""
                                UPDATE games
                                SET money = money - ?
                                WHERE member_id = ?
                                """, (money, member_id))
                d.execute("""
                                                UPDATE games
                                                
                                                SET miximax = ?
                                                WHERE member_id = ?
                                                """,
                          (miximax, member_id))
                conn.commit()```
#

well miximax is wrongly tabulated but in python is good

frosty parrot
#

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

#

what to do ?

spice zenith
dull terrace
spice zenith
#

oh yeah u forgot ctx ig

spice zenith
dull terrace
#

i have no idea if it's an asynchronous function or not

frosty parrot
#
async def embed(self, ctx):
    embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange)

    embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
    embed_message.set_thumbnail(ul=ctx.guild.icon)
    embed_message.set_image(url=ctx.guild.icon)
    embed_message.add_field(name="Field name", value="Feild value", inline=False)
    embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)```
#

i did this

spice zenith
#

why ctx.author.mention

#

it is easier to do a interaction command and do an interaction.user imo

frosty parrot
#

What to do now ?

slate swan
#

my bot is not showing correct guilds member pls tell me how to fix this

#
memberCount = len(set(bot.get_all_members()))
    await ctx.send(f"So im in {serverCount} guilds with a total of {memberCount} members. :smiley:\nIm running python {pythonVersion} and discord.py {dpyVersion}")
    ```
spice zenith
frosty parrot
slate swan
spice zenith
dull terrace
#

oh you're trying to get the total members

slate swan
dull terrace
#

do you have permissions for that

slate swan
slate swan
slate swan
dull terrace
#

try that

#

or py total_members = sum(guild.member_count for guild in bot.guilds)

slate swan
#

!d discord.Client.get_all_members

unkempt canyonBOT
#

for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") the client can see.

This is equivalent to:

```py
for guild in client.guilds:
    for member in guild.members:
        yield member
spice zenith
#

cause i cant find it either:""""")

dull terrace
spice zenith
#

how should i do that?

radiant bough
#

I don’t think so

spice zenith
#

it isnt i think

#

but im explaing to him how to do it as a slash command

#

in dm

radiant bough
#

You forgot the r ryuko

radiant bough
spice zenith
brazen raft
slate swan
slate swan
#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

slate swan
#

the only members visible is the bot's member itself

#

so how to get member intents

#

@slate swan

#

enable from dev portal and enable in your code using your discord.Intents instance

#

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

okay i am sending whole code of bot just wait

brazen raft
#

The constructor suffices