#discord-bots

1 messages Β· Page 46 of 1

deep osprey
#
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
    async with aiofiles.open('allowed_channels.txt', mode='a') as f:
        contents = await f.read()
        if channel.id not in contents:
            await ctx.reply("Successfully added!")
            await f.write(f"\n{channel.id}")
            await f.write("\n")            
        else:
            await ctx.reply("Already there!")``` still doesnt work
bold pewter
#

Mmm is there any chance we are getting new api stuff in discord.py?

silk fulcrum
glad cradle
bold pewter
#

Slash commands ,buttons that kinda of stuff

unkempt canyonBOT
silk fulcrum
#

go use them

bold pewter
#

Can you give me a example for slash commands in discord.py 2.0?

slate swan
#

no, something like

class Bot(commands.Bot):
     def __init__(self):
          super().__init__(...)
          self.add_command(self.uwu)
     
    @commands.command()
    async def uwu(self, ctx): ...```
modifications can be done as required
silk fulcrum
#

oh

slate swan
#

I'm totally not sure how it would work since never tried it, i might be wrong

bold pewter
deep osprey
bold pewter
#

How do i add options that only allow to choose channels?

slate swan
silk fulcrum
#

bruh, it blocked the link

deep osprey
torn sail
silk fulcrum
#

@unkempt canyon do you have antirickroll or what?

slate swan
bold pewter
#

Mmmm

bold pewter
#

Where do i put it sadCat

glad cradle
#

"how to type hint"

#

as expected

silk fulcrum
#

?tag typehinting

novel apexBOT
#

This is not a Modmail thread.

silk fulcrum
#

gah

bold pewter
#

I need a full blown video tutorial 4912sadgepray

slate swan
#

!typehint

unkempt canyonBOT
#

Type Hints

A type hint indicates what type a variable is expected to be.

def add(a: int, b: int) -> int:
    return a + b

The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.

It's important to note these are just hints and are not enforced at runtime.

add("hello ", "world")

The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.

Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.

mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.

slate swan
bold pewter
#

I just realised

#

*found

#

Pycord has everything peepoVERYHappy

slate swan
bold pewter
#

It's simpler

slate swan
#

pycord is shittier, use disnake

bold pewter
#

@bot.slash_command

#

That's it peepoVERYHappy

slate swan
#

I dont see how dpy is complicated either

#

it uses a single decorator too

bold pewter
#

Discord.py doesn't have good documentation for slash commands

slate swan
#

what....

glad cradle
#

πŸ’€

#

it's probably you who can't search

silk fulcrum
#

2nd pin, link what i just sent, rickroll

glad cradle
#

don't

slate swan
#

pov: stable/index.html

glad cradle
slate swan
#

I had examples in the gist too...

winged dock
#

the code doesnt send why?

slate swan
#

nice formatting

winged dock
#

Woops

#

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

#
@bot.command()
async def rules(ctx):
    embed=discord.Embed(title="1. No NSFW Content this includes links, images, featuring 18+ content.                              2. No gambiling this includes flip, stake and any other betting sites.              3. Please do not use this server as a market place !                 4. No self promo or spam without permission from a mod or owner. (this includes advertisments and invite links)                              5. Any users who fail to follow discords terms will be prosecuted.                   πŸ”— https://discord.com/terms")
    await ctx.send(embed=embed)
#

There

slate swan
#

errors?

winged dock
#

Nope.

#

Runs just doesnt send.

slate swan
#

how do you know it runs

winged dock
#

Beacuse i try my other cmds

#

They work

slate swift
#

bro when I nuke a channel/purge a channel how can I make the bot say Cleared by {user} i've tried a bunch of ways

bold pewter
winged dock
winged dock
slate swift
slate swift
winged dock
#

Send your code and sure

slate swan
slate swift
#
async def nuke(ctx, amount=10000000):
    await ctx.channel.purge(limit=amount)
    await ctx.send("Cleared by ``{user}``")```
winged dock
#

Or do that

slate swift
#

I'm doing nuke instead of purge

#

so it clears whole channel

slate swan
#

what thats not a thing either

winged dock
#

Yup

glad cradle
winged dock
#
@bot.command()
async def nuke(ctx, amount=10000000):
    await ctx.channel.purge(limit=amount)
    await ctx.send("Cleared by ``{ctx.author}``")```
slate swift
winged dock
slate swan
winged dock
#

Okay

glad cradle
bold pewter
winged dock
#

I did

slate swan
#

and

glad cradle
#

Bot got destroyed

slate swift
slate swan
#

nice

glad cradle
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

bold pewter
slate swift
#

oh

slate swan
#

floppy

glad cradle
#

disk

bold pewter
#

Yea?

slate swan
#

swear that you wont use pycord

bold pewter
slate swan
glad cradle
#

you should write your own library instead of using pycord, it would be better

bold pewter
glad cradle
#

it's so magnetic

slate swan
#

the touch is

bold pewter
glad cradle
#

btw I'm cooking a cake

#

who wants a piece

slate swan
#

baking*

bold pewter
#

Baking a cake

glad cradle
#

cook

#

πŸ‡¨πŸ‡°

bold pewter
#

Bake

slate swan
slate swift
#

can someone help me make a simple join on dm message for all servers my bot is in i wanna make the bot say the support server?

bold pewter
slate swan
bold pewter
#

!on_member_join

glad cradle
bold pewter
#

Mm

slate swift
bold pewter
slate swift
slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
glad cradle
slate swan
#

!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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
glad cradle
slow fog
slate swan
#

websi

slate swift
#

So no async def? just async

slate swan
#

...

bold pewter
#

async def

slate swift
#

ik

glad cradle
#

lmao

slate swift
#

i wanted to see what yall would say

slow fog
bold pewter
slate swift
slate swan
#
async with def as fn:
    await fn foo(): 
          async with print as p: 
             await print("uwu")

yes.

glad cradle
slate swan
slate swift
#

sence it isnt a command

glad cradle
#

that's obvious

robust fulcrum
#

Guys i made a comand that takes a user argument like this mem:discord.Member the mem will be the member object and i can i do this await mem.timeout?

slate swift
bold pewter
glad cradle
mild lava
#

im back once again

slow fog
mild lava
#
Traceback (most recent call last):
  File "D:\Projects\temp\yuno\bot.py", line 81, in <module>
    bot.run(os.getenv('DISCORD_TOKEN'))
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Program Files\Python\3.10\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\Python\3.10\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\client.py", line 589, in login
    await self.setup_hook()
  File "D:\Projects\temp\yuno\bot.py", line 42, in setup_hook
    await self.tree.sync(guild=guild)
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\app_commands\tree.py", line 1070, in sync
    data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
  File "D:\Projects\temp\yuno\.venv\lib\site-packages\discord\http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
dull terrace
#

how do i import from another directory 7739monkathink trying to organize code, in font i want to import something from config

mild lava
glad cradle
mild lava
#

the problem is im not Danny, so i guess i cant use the example code πŸ˜”

dull terrace
#

is doing stuff like this to make things a fraction faster and life easier dumb? 7739monkathink

#

so if i need a link button i can just do link.button.patreon

glad cradle
#

Enum exists

heavy folio
mild lava
heavy folio
mild lava
#

probably shouldnt be coding at 5 am

dull terrace
#

looked into enum, idk if it's that useful here seeing as im the only person working on the code 7739monkathink

rugged shadow
slate swan
slate swan
cerulean shale
#
extensions=[
  'cogs.afk',
  'cogs.anime',
  'cogs.chatbot',
  'cogs.embeds',
  'cogs.events',
  'cogs.fun',
  'cogs.minigames',
  'cogs.moderation',
  'cogs.nsfw'
]

if __name__ == "__main__":
  for extension in extensions:
    try:
      await bot.load_extension(extension)
    except Exception as e:
      print(f"Error loading the {extension}", file=sys.stderr)
      traceback.print_exc()

await bot.load_extension("jishaku")
glad cradle
#

the error is pretty self explanatory

cerulean shale
#

it is showing that it was never awaited if i dont use await

glad cradle
#

await keyword can only be used inside async function

cerulean shale
glad cradle
#

I'm sending a message for you

#

A change in discord.py 2.0 made all methods related to extensions & cogs async.

Bot.load_extension(), Bot.unload_extension(), Bot.reload_extension(), Bot.add_cog(), and Bot.remove_cog are all coroutines now. This means you need to await them. Functions setup and teardown in extensions must be coroutines now. This means you need to define them with async def.

What is the purpose of this change?
It allows the setup and teardown functions of extensions to be coroutines.

async def setup(bot):
     await bot.add_cog(Commands(bot))

async def teardown(bot):
    return

View more:
Read more about the changes and how you can start your bot here: https://discordpy.readthedocs.io/en/latest/migrating.html#migrating-2-0-commands-extension-cog-async

glad cradle
#

open the link

#

and read

cerulean shale
#

ight its loading

#

got it

#
class MyBot(commands.Bot):
    async def setup_hook(self):
        await self.load_extension('my_extension')

in 'my_extension' place, i can make a list called extensions or so and replace it without ''???

slate swan
#

or instead of doing that

#
import os

#an async context

[await self.load_extension(f"cogs.{file[:-3]}") for file in os.listdir("cogs") if file.endswith(".py") and not file.startswith("_")]
cerulean shale
#

ohk

#

thx i will try πŸ₯²

slate swan
#

that basically prevents you from having to have a list of all cogs

#

it dynamically searches for any cogs even if you add new ones

cerulean shale
#

thx

slate swan
glad cradle
slate swan
glad cradle
#

coz watermelon says so

slate swan
#

that's an iteration over a list

#

not a custom iterator

glad cradle
#

then watermelon is a bad suggester

slate swan
#

who even is watermelon

#

lmao

glad cradle
#

it's you

slate swan
#

jeez

#

alright, my bad

glad cradle
#

πŸ¦†

mild lava
#

aight so i finally got my slash command to work

#

only problem now is, after syncing to a specific guild while testing, and then syncing globally, i have duplicate commands in my testing server

#

is there a way to clear guild-specific commands and only keep the global ones?

slate swan
#

either clear all the slashes and sync again

#

or deal with it

mild lava
#

then how does discord.py expect us to handle all these commands

slate swan
#

handle?

mild lava
#

how exactly do i clear them?

slate swan
#

just

#

comment out all of them and run your bot which will sync an empty tree with the api, and then uncomment your commands and run it and it'll sync all the commands to the api

mild lava
#

thats a very manual workaround

slate swan
#

yes it is

mild lava
#

*cough* wonder what this is

slate swan
#

but whatever way works ASakashrug you'll have to still run the code twice

mild lava
#

now to make it automatically clear any guild-specific commands when doing a global sync....

#

looks like im not getting any sleep tonight thisisfine

slate swan
#

use the guild kwarg

#

self.bot.tree.clear_commands(guild=discord.Object(id=1234567890987654321))

mild lava
slate swan
#

and sync the commands since it only clears the commands from the local cache

mild lava
#
for guild in self.bot.guilds:
    self.bot.tree.clear_commands(guild=guild)
    self.bot.tree.sync(guild=guild)
self.bot.tree.sync()

idk why im typing this here and not in my ide

slate swan
mild lava
#

syncing global commands doesnt affect guild commands

slate swan
#

also if you wanna clear all the commands, just dont specify the guild kwarg

#

yes.

#

I know

mild lava
#

if i just clear global commands, all the testing commands will stay

#

so i need to get rid of those

#

theres only 2 guilds anyways

unkempt canyonBOT
#

Hey @cerulean shale!

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

cerulean shale
#

are there any mistakes in my cog?

mild lava
vocal snow
cerulean shale
#

i recently decided to shift to cogs

vocal snow
#

a lot of those error handlers should be condensed into a global handler instead of command-specific ones

cerulean shale
#

i made a load command but even then it aint, it is not even giving any errors

cerulean shale
vocal snow
#

maybe. I'm just saying it's a lot of unnecessary code

robust fulcrum
#

Guys why i am getting this error

vocal snow
#

Missing Permissions

robust fulcrum
vocal snow
#

There are are like 4 different errors here

#

are you printing the error in your handler

cerulean shale
robust fulcrum
vocal snow
#

yes

#

don't print it

robust fulcrum
#

Do i do raise error?

vocal snow
#

raise the error or use the traceback module

robust fulcrum
#

Ok I'll use traceback module

ionic edge
#
    @commands.hybrid_command(name='response' , description = 'Gives The Response')
    @app_commands.guilds(1008758498789695508)
    @app_commands.checks.has_role(1010100433538273300)
    async def response(self,ctx, * , member : discord.Member , response : Literal['accept', 'reject']):
        channel = self.client.get_channel(1010106207865933934)  
        if (response == 'accept'):
            await channel.send(f'{member.mention} has been accepted')
            await ctx.send(f" {member}'s Form ||Accepted|| By {ctx.author.mention}")
        if (response == 'reject'):
            await channel.send(f'{member.mention} has been declined')
            await ctx.send(f" {member}'s Form ||Rejected|| By {ctx.author.mention}")```
#

this is my code

#

this command is not working

#

but the slash command is working

robust fulcrum
vocal snow
#

well it's giving you Missing Permissions for something

robust fulcrum
cerulean shale
#

can i do this?

  @commands.Cog.listener()
  async def on_message(self, message):
    if message.author == bot.user:
        return
      
    elif message.content.lower() == 'no u':
      await message.channel.send('no u')

    elif message.content.lower() == 'f':
      await message.channel.send(f'{message.author.display_name} paid their respects.')

    elif message.content.startswith('i am'):
      value = message.content.split("i am ", 1)[1]
      await message.channel.send(f'Hello {value}, I am Dad.')

    elif message.content.startswith('imagine'):
      value = message.content.split("imagine ", 1)[1]
      await message.channel.send(f'I can\'t even imagine {value}.')
vocal snow
robust fulcrum
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
#

the bot's role needs to be higher than whoever it's doing an action on

robust fulcrum
robust fulcrum
silk fulcrum
#

and check if isinstance(error, commands.MissingPermissions)

cerulean shale
deep osprey
#
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
    async with aiofiles.open('allowed_channels.txt', mode='a') as f:
        contents = await f.read()
        if channel.id not in contents:
            await ctx.reply("Successfully added!")
            await f.write(f"\n{channel.id}")
            await f.write("\n")            
        else:
            await ctx.reply("Already there!")``` why doesn't that work? no output or errors
vocal snow
#

why are you using a txt file?

#

just use json or pickle or something

deep osprey
#

is there any tutorial?

vocal snow
#

im not sure, if you google it you'll probably find something since they are very common forms of serialization

deep osprey
#
silk fulcrum
#

yeah, there is pretty much enough for you

vocal snow
#

that doesn't show how to use it with files

silk fulcrum
#

oh yeah bruh

vocal snow
#

this is better @deep osprey

#

depending on what you're doing a db might be better as well

deep osprey
#

which is easier and faster?

silk fulcrum
#

there is about files

vocal snow
robust fulcrum
#
    @mute.error
    async def muteerr(self,ctx,error):
        if isinstance(error, commands.MissingPermissions):
            embe = errorembed.error()
            embed = embe.perm("kick_members")
            await ctx.send(embed=embed)

Guys why this error handler not working
My bot is raising the error instead of handling it

vocal snow
#

if you're just going to be storing channel IDs json is fine

deep osprey
#

i am just storing channel ids

silk fulcrum
#

show it's code

robust fulcrum
silk fulcrum
robust fulcrum
#

Fine

robust fulcrum
# silk fulcrum <@893363878728192041>
class error:
    def missingargs(self,args):
        args = str(args)
        embed = Embed(
            title = "Missing argument ",
            description = f"`{args}` was not provided",
            color = Color.red()
        )
        return embed

    def voiceerror(self):
        embed = Embed(
            title = "Voice channel",
            description = f"Please join a voice channel first",
            color = Color.red()
        )
        return embed

    def perm(self,perm):
        embed = Embed(
            title = "Missing permission",
            description = f"Missing `{perm}` permission",
            color = Color.red()
        )
        return embed
pulsar solstice
#

pls

bold pewter
pulsar solstice
#

I love coding bots but there is no way to get it 24/7

silk fulcrum
deep osprey
#
data = {
    "channels": {
        "id1": "112233",
        "id2": "332211"
    }
}``` so is this an example of json file?
silk fulcrum
#

i see

robust fulcrum
bold pewter
#
{
    "channels": {
        "id1": "112233",
        "id2": "332211"
    }
}
silk fulcrum
silk fulcrum
vocal snow
#

Why the dictionary

#

Just have a list directly

silk fulcrum
deep osprey
silk fulcrum
vocal snow
#

Json != Dictionary

silk fulcrum
#

and what?

#

oh i see

#
{"channel_ids":[11243241, 13251236]}```
vocal snow
#
[
    111,
    22,
    33,
]
silk fulcrum
#

wait what

#

json can hold just a list of ids?

robust fulcrum
silk fulcrum
robust fulcrum
idle haven
#

Hey

vocal snow
#

!e ```py
import json
json.loads("[1,2,3]")

unkempt canyonBOT
#

@vocal snow :warning: Your 3.11 eval job has completed with return code 0.

[No output]
vocal snow
robust fulcrum
silk fulcrum
robust fulcrum
#

Error raises?

silk fulcrum
#

what error

robust fulcrum
#

The error it is giving

#

What are you trying to say?

silk fulcrum
#

can you send traceback?

robust fulcrum
#

Ok

deep osprey
#
{"channels":[11243241, 13251236]}``` so this should be my json file?
robust fulcrum
silk fulcrum
#
[35435425, 575868]``` should be in it
deep osprey
#

just a list without a name?

silk fulcrum
#

oops ping

deep osprey
#

then how am I gonna check if the channel.id in that json file?

silk fulcrum
#

if channel_id in loaded_list

#

whats the problem

deep osprey
#

sorry but I still don't get why using json is better than using .txt file?

vocal snow
#

It handles the serialization for you

#

And if required you can store more complex data

#

Besides, txt files aren't meant for this

deep osprey
#

so do I have to add manually channel ids in the code of the bot?

#

or the command handles that?

vocal snow
#

I'm not sure what you're saying

#

In the command you just append the new channel ID to the list

deep osprey
#

without json, it does that but when I restart my bot, channel ids are removed

#

would json fix that?

vocal snow
#

Yes

#

Since you're writing to storage

deep osprey
#
channels = [1008214910498508872]
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
    with open("data.json", "w+") as f:
        json.dump(channels,f)``` so this should be my code?
glad cradle
#

why you have channel as parameter if you don't use it

deep osprey
#

I will use it later but I am just making sure if this is the correct way

vale wing
unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
deep osprey
slate swan
#

anyone elses portals keep loading?

slate swan
#

o

#

just had to clear cache

#

problem fixed

pale turtle
#

This is not 100% discord-bot related, but I would like some help. I am trying to make a leveling system, that every message is around 20 xp. I am having trouble on how to make the ranks, as in what rank should the member be by his xp. I need an algorithm I guess, but no idea what algo and how to use it in the code. Anyone can suggest any idea?

simple kettle
#

is there a way to get rid of these kind of errors? Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "suuke" is not found

slate swan
#

but okay, since there are a lot of other ways to do the same

novel prairie
#
@bot.command(aliases=['makerole'])
@commands.is_owner()
async def createrole(ctx, *, name):
    embed = discord.Embed(
        title=f"""**{ctx.author.name} Created A Role Named: | {name} | **""",
        color=000000)
    guild = ctx.guild
    await guild.create_role(name=name)
    await ctx.reply(embed=embed)``` ```py
  File "main.py", line 480
    async def createrole(ctx, *, name):
    ^
SyntaxError: invalid synta``` whats going on with replit lmao how can i fix this?
vocal snow
#

Send full code

novel prairie
#

oh wait nvm i fixed it

#

i want to use rgb colors in a embed i tried this: py color=discord.Color.from_rgb(ff0000))) but it didnt work

vocal snow
#

That isn't rgb

#

!d discord.Colour.from_rgb

unkempt canyonBOT
#

classmethod from_rgb(r, g, b)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from an RGB tuple.
vocal snow
#

See the params

novel prairie
#

so what do i need to change?

vocal snow
#

That's for you to decide

novel prairie
#

like that? py color=classmethod from_rgb(ff, 00, 00)

#

@vocal snow

ionic edge
#

io wanna make it respond

novel prairie
#

huh?

ionic edge
#

The application did not respond

ionic edge
#
        if (response.lower() == 'accept'):
            response = discord.Embed(title='Form Response' , description = f"**Hey {member.name} , \n \n :aarow: Your form has been accepted..! :555rainbowhearts: \n :aarow: Go Through The Rule Book Once :receipt: \n :aarow: Make sure to go through [#1010106220755034132](/guild/267624335836053506/channel/1010106220755034132/) to get the server iP and Hop in !! \n \n  Happy RPing..!! **", color=0xa434eb)
            response.set_footer(icon_url=member.avatar)
            response.set_thumbnail(url = guild.icon)
            await channel.send(member.mention,embed = response )
            await member.add_roles(role)
            await ctx.response.send_message("Done!!")
            await log.send(f" {member}'s Form ||Accepted|| By {ctx.author.mention}")```
vocal snow
#

If you want to use a hex value then you can pass a hex literal to discord.Color directly

spring flax
#

is that a prefix command?

slate swan
ionic edge
spring flax
#

then why are you using ctx?

#

interaction is the convention for that. ctx is convention for prefix commands

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
spring flax
#

Use attributes from the class above

ionic edge
#

hybrid command

#

@spring flax

spring flax
#

never used that. Not sure how it works

maiden fable
spring flax
#

Uhh no I don't think so

maiden fable
slate swan
#

Why are programming memes so cringe

dull terrace
#

i can't take any more organizing but i've only finished the config and utils so far pepe_cry

slate swan
#

why-

vocal snow
#

when each file has 1 line of code

slate swan
#

too smart

dull terrace
#

it's just under 5k lines of code total

slate swan
#

that's not much corresponding to the amount of files

#

that's even further going than django

dull terrace
#

idk, all the sections make sense in my brain and they're all probably going to grow in size by the time im done ablobsweats

slate swan
#

that's cool, all the best 02love

maiden fable
maiden fable
robust fulcrum
#

Guys how can I check the user have mute permission (text channels)?

dull terrace
#

should probably at some point

maiden fable
#

Tf is that?

dull terrace
#

you never throw stuff in pickle when you're being lazy?

vocal snow
#

Marshal !!

maiden fable
#

Ngl, I am hearing the module's name first time but people say pickle is better?

maiden fable
dull terrace
#

pickle is very slow but easy

#

you can basically throw any object into it to save

maiden fable
#

Not any object iirc
U can't throw in things like invite objects, can u?

dull terrace
#

you can't put in discord objects, tried that when i was first starting out doge_kek

maiden fable
#

That's sad ngl

vale wing
#

It was breaking every month and I was losing all the data lmfao

dull terrace
#

i had one massive dictionary that was about 5 layers deep

#

containing every user

slate swan
robust fulcrum
#

@slate swan

slate swan
#

!d discord.Permissions.moderate_members

unkempt canyonBOT
robust fulcrum
slate swan
#

how to make welcome messgae in nextcord? Video's code not working

silk fulcrum
vale wing
#

Video tutorials bad

#

Read the docs πŸ‘

silk fulcrum
#

this πŸ‘

#

I think I found tutorial they watched

slate swan
#

hi guys how can i add a button to button. i have a shop command (.shop) which brings up multiple buttons to different things i sell. once they’ve chosen a tool to preview i want to add a buy button and a back button. can anyone help me with that

silk fulcrum
#

to add buttons to the view you just do view.add_item(new_button) for each button and then edit the message with that view await message.edit(..., view=view)

slate swan
#

oh ok

#

so i’m just editing the message so it sends another button?

silk fulcrum
#

what did you not unsertand?

slate swan
#

well ik how to add buttons with .add_item

silk fulcrum
#

if you want to remove a button and place the other instead do view.remove_item(old_button) and then view.add_item(new_button)

slate swan
#

ye i don’t want remove it i just want to add a button to the new message

#

it’s kind of hard to explain i’ll try find an example

silk fulcrum
#

ok...

vale wing
silk fulcrum
#

why not edit

hushed galleon
#

thats common practice? you can edit the message with your new components too

vale wing
#

Why are people so word picky

silk fulcrum
#

πŸ€“ 😳

cold sonnet
#

why is the implementation of interactions so bad

slate swan
#

blame discord API for that

#

how would that work though because i’m not trying to just edit or delete the button i’m trying to add a new one once they’ve clicked on a button

cold sonnet
#

nah I literally mean danny changed everything but it was so unnecessary

maiden fable
cold sonnet
#

what's the point of interaction.send_message instead of interaction.send

#

it's so inconsistent

slate swan
#

because when u make a button and press it it gets rid of what u just pressed

hushed galleon
#

@slate swan id suggest having your view keep track of which item the user has selected and on click, update all the buttons your view will have afterwards

slate swan
slate swan
#

or maybe im mixing up libraries

vale wing
cold sonnet
#

never heard of that

slate swan
cold sonnet
#

yeah... hikari maybe?

slate swan
#

they renamed some stuff from message to response though

silk fulcrum
cold sonnet
#

is a modal sent in a message

vale wing
#

Why is it named like some anime thing

silk fulcrum
#

hikari weird

silk fulcrum
hushed galleon
#

its just a word for light

slate swan
cold sonnet
silk fulcrum
cold sonnet
#

andrew tate's dad

vale wing
silk fulcrum
vale wing
cold sonnet
#

light.lightbulb

hushed galleon
slate swan
slate swan
#

hikari tends to be low levelled

vale wing
#

!d nextcord.on_member_join

silk fulcrum
slate swan
#

so it does not have an inbuilt cmd handler

unkempt canyonBOT
#

nextcord.on_member_join(member)``````py

nextcord.on_member_remove(member)```
Called when a [`Member`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Member "nextcord.Member") leaves or joins a [`Guild`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Guild "nextcord.Guild").

This requires [`Intents.members`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Intents.members "nextcord.Intents.members") to be enabled.
vale wing
silk fulcrum
vale wing
#

Listen for this

slate swan
vale wing
vale wing
#

Ah yes, that's the common practice

dense cedar
#

Hello, I have a Discord bot in Python. There is an embed message in the ticket section of my bot. To open the ticket, I want to change the message in the embed and send the embed again.

supple ridge
dense cedar
supple ridge
sage otter
#

You can do something along the lines of

emb = discord.Embed(description="hi")
msg = await ctx.send(embed=emb)
emb.description = "hello"
await msg.edit(embed=emb)
#

This is an example

#

Just assign your embed object to a variable. Edit it after you send the original embed and edit the message you sent with the new embed

spare urchin
#
@client.slash_command(name='emojiinfo', description='Shows info about an emoji')
async def infofemoji(ctx, emoji:str=SlashOption(description='Valid emoji in the server')):
  name = emoji.name

im trying to make an emoji info command
As you can see here I passed in emoji as str and it gives me error saying that str object has no attribute name
If i try to pass in emoji as nextcord.Emoji it will not work as nextcord.Emoji cant be used in slash commands
Is there a way i can resolve this issue??

hollow rivet
#

What can you do with discord.py without creating a bot account

silk fulcrum
#

printing it's version

#

getting errors

#

deleting it

hollow rivet
#

There's no way to interact with discord without a bot account then?

silk fulcrum
#

it's designed for discord bots so

#

idk maybe im stupid and it has functionalities for applications, not bots

#

but iirc it doesn't

hollow rivet
#

I'm trying to pull some messages from a group dm automatically, is that possible?

sage otter
#

It’s not python tho

#

It’s php.

silk fulcrum
#

php good

#

php has laravel btw, which is good

#

so php good

hollow rivet
#

Idk php

silk fulcrum
#

learn php

#

it's good

sage otter
#

idk about all of that.

silk fulcrum
#

!pypi restcord

unkempt canyonBOT
#

Restcord is a rest API wrapper for the Discord API, but this one does not include WebSockets, this is for people who dont want websockets but only make requests to the api.

silk fulcrum
#

wait what 😳

sage otter
#

Which isn’t allowed

hollow rivet
#

I see

#

Why not allow self bots and give them limited access

#

It seems self bots are useful

shrewd apex
#

there is everything nowadays

silk fulcrum
sage otter
#

I only knew of phps restcord πŸ€·β€β™‚οΈ

spare urchin
glad cradle
hollow rivet
# unkempt canyon

`import restcord
import asyncio

loop = asyncio.get_event_loop()
client = restcord.Restcord(token="Your token here")

async def test():
guild = await client.get_guild("Some guild id of a guild that ur bot/user account is in")
print(guild.dict)

loop.run_until_complete(test())`
In the examples it says this, does that mean you can use it with a user account

hollow rivet
sage otter
#

I recommend not doing whatever you're thinking about doing with that library. No matter if the reason is good or not, Discord doesn’t want you automating your account

glad cradle
hollow rivet
#

You can't invite a bot to a group dm

glad cradle
#

but it should be a Group DM

glad cradle
#

I'm not sure with the Dm things

hollow rivet
#

How do you even add a bot to your friend list

glad cradle
#

with the sussy magic

hollow rivet
#

??

shrewd apex
hushed galleon
#

you can still find it documented in the 1.7.3 version of dpy before they removed support for it entirely

hollow rivet
#

I guess i'll figure something out ty

spare urchin
#
@client.slash_command(name='emojiinfo', description='Shows info about an emoji')
async def infofemoji(ctx, emoji:str=SlashOption(description='Valid emoji in the server')):
  name = emoji.name

im trying to make an emoji info command
As you can see here I passed in emoji as str and it gives me error saying that str object has no attribute name
If i try to pass in emoji as nextcord.Emoji it will not work as nextcord.Emoji cant be used in slash commands
Is there a way i can resolve this issue??

vale wing
sick birch
#

Well you still need a bot token or your oauth access token

vale wing
#

Yes

#

I just scrolled the conversation and found out he might need this

hollow rivet
#

Guys, if you need a bot to do stuff, what are these other checkboxes for

vale wing
#

One sec ima link you the table

slate swan
#

bot & application.commands ( if you want app commands)

vale wing
slate swan
#

whats the messages.read scope? something like message intents?

hollow rivet
#

What is an "app" exactly, is it just the program?

sick birch
#

An app is one step higher than your bot

#

A bot is part of an app

#

An app can also be discord RPC for your game, it can also be an oauth thingy

hollow rivet
#

What's rpc

vale wing
#

Rich presence

hollow rivet
#

Mhm ok

vale wing
sick birch
#

Developers of games can hook up discord to it so that other discord members can see what you’re doing inside of a game

hollow rivet
#

How do i get discord aproval

vale wing
#

In case of bots the token is given in a bit different way than oauth

vale wing
hollow rivet
#

Isn't that what i'd need to get the messages from the group dm

vale wing
#

Why do you need to get messages from there

hollow rivet
#

Cuz people say some funny stuff there and i want to automatically do stuff with it

sick birch
#

You can ask discord but I doubt the likelihood of it

vale wing
#

Why can't they say funny stuff in a server

#

what's the point of group DMs anyway

hollow rivet
#

Cuz we already have the group dm

manic aurora
#

is there a way to send a messages for new commits in Github?

silk fulcrum
#

why can't you add the bot to your group

vale wing
manic aurora
hollow rivet
#

Alright its whatever

manic aurora
#

or what should i look for

silk fulcrum
unkempt canyonBOT
#

The PyPA recommended tool for installing Python packages.

hollow rivet
silk fulcrum
unkempt canyonBOT
vale wing
#

Ah yes pip install pip

silk fulcrum
sick birch
vale wing
# unkempt canyon

Screw wrappers I am raw requests man (except discord because too much stuff)

hollow rivet
hollow rivet
vale wing
hollow rivet
#

Lol wut then i'd still need a self bot

sick birch
#

sometimes I feel like a bot

#

just wake up and beep beep boop boop πŸ€–

hollow rivet
#

Don't we all

silk fulcrum
#

beep boop baap

hollow rivet
#

;)

manic aurora
vale wing
#

Imagine using github wrapper

silk fulcrum
#

bruh i think that lib is dead

manic aurora
vale wing
#

What version does github API have rn

manic aurora
#

so is there any way to send if there's a commit without that library?

vale wing
silk fulcrum
vale wing
#

Why do y'all even use wrappers for so easy APIs

silk fulcrum
#

docs links in pypi are not working

silk fulcrum
slate swan
silk fulcrum
#

bruv

slate swan
slate swan
vale wing
shrewd apex
#

how that even matter pithink since PPL made them let's do them a favour and use it

#

if it's like just a smol usage u can make ur own ig tho

cerulean shale
#

import discord
import http
import aiohttp
from discord.utils import get
from discord.ext import commands
from aiohttp import ClientSession 

class Chatbot(commands.Cog):

  def __init__(self, bot):
    self.bot = bot

  @commands.Cog.listener()
  async def on_message(self, message):
    cmdChannel = self.bot.get_channel(1008668481484500992)
    inp = message.content
    
    if message.author == self.bot.user:
      return
    
    elif message.channel.id != cmdChannel.id:
      return
    
    else:
      async with aiohttp.ClientSession() as cs:
      async with cs.get(f'https://api.popcat.xyz/chatbot?msg={inp}&owner=Ricky&botname=Estelle') as r:
        res = await r.json()

    await message.send(f"{response}")


async def setup(bot):
  await bot.add_cog(Chatbot(bot))
#

HELP IT AINT WORKING ;-;

potent spear
# cerulean shale HELP IT AINT WORKING ;-;
@commands.Cog.listener()
  async def on_message(self, message):
    cmdChannel = self.bot.get_channel(1008668481484500992)
    
    if message.author == self.bot.user:
      return
    
    if message.channel.id != cmdChannel.id:
      return

    msg_content_without_spaces = message.content.replace(" ", "+")
    async with aiohttp.ClientSession() as cs:
      async with cs.get(f'https://api.popcat.xyz/chatbot?msg={msg_content_without_spaces }&owner=Ricky&botname=Estelle') as r:
        res = await r.json()

    await message.channel.send(f"{res}")```
#

2 problems:

  1. there's no such thing as message.send
  2. response wasn't defined, you probably meant res
cerulean shale
#

shouldnt we get the results from api?

sick birch
#
  1. don't make a new aiohttp.ClientSession for every request
cerulean shale
#

.

#

ok will try

potent spear
#
  1. you can't have spaces in urls, so if your message content contained them, your url would've been invalid
    spaces usually get replaced by + in urls, but you can use dedicated libs to "convert" strings to valid urls etc
potent spear
cerulean shale
#

i am shifting over to cogs as my code was getting messy

#

and i somehow got 2 of my other cogs work

#

and now i am tryint to fix this cog and i use load command to load the cogs as i am still on fixing my cogs first

slate swan
cerulean shale
#

any idea on how i can do it?

slate swan
#

.replace(" ", "%")

#

jeez

vocal snow
#

you shouldn't need to do that manually

#

surely aiohttp handles url encoding

potent spear
potent spear
ionic edge
#
if channel in category.channels:```
#

getting error

#

discord 2.0

potent spear
#

sharing the error would help...

ionic edge
#

if channel in category.channels:
AttributeError: 'NoneType' object has no attribute 'channels'

potent spear
#

your category is NOne

#

how did you define it?

ionic edge
#

yes

potent spear
#

I'm not asking you if, I'm asking how

ionic edge
#

helpcategory = 1010580194916057128

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

#

category = guild.get_channel(helpcategory)

potent spear
#

and now in codeblocks

#

or just

#

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

radiant parrot
#

can someone help, my discord bot seems to not be seeing messages or just not replying

vocal snow
#

if you're on 2.0 make sure to enable message_content intents

radiant parrot
#

how do u do that again? thhx

vocal snow
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

vocal snow
#

!d discord.Intents.message_content

unkempt canyonBOT
#

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

β€’ The message was sent by the client

β€’ The message was sent in direct messages

β€’ The message mentions the client

This applies to the following events...

potent spear
# unkempt canyon

this is outdated since v2 became stable
the code still works, just the explanation isn't complete

vocal snow
#

well it does mention message content in the first para

#

i think its complete, am I missing something

potent spear
#

yup, I was wrong

#

I thought message_content would've been enabled by default in v2, I guess not

radiant parrot
#

let me send my code in as still hvaing an issue πŸ™‚

potent spear
#

nice codeblocks

radiant parrot
#

haha

potent spear
#

you forgot to pass in the intents in the Client constructor

vocal snow
#

and consider using the commands extension instead of parsing the command manually

potent spear
#

discord.Client(..., intents = intents)

vocal snow
#

you also forgot to enable the message content intents

#

which is kinda the main issue

potent spear
#

seemed like a copy pasta to me

radiant parrot
#

its my mate's code that he wants to implement on server

#

still dnt wanna work :/

potent spear
#

you most likely never toggled the message content intent on in discord dev portal

vocal snow
#

putting code examples in tags is a double-edged sword

ionic edge
#
    for key, value in dmhelp.items():
RuntimeError: dictionary changed size during iteration```
#
    @commands.command()
    async def closeticket(self,ctx ):
        guild = self.client.get_guild(1008758498789695508)
        category = guild.get_channel(1010580194916057128)
        channel = ctx.channel
        if channel in category.channels:
            with open(r"dmhelp.json","r") as f:
                dmhelp = json.load(f)
            for key, value in dmhelp.items():
                if value == channel.id:
                    user = guild.get_member(int(key))
                    del dmhelp[key]
                    with open(r"dmhelp.json","w") as f:
                        json.dump(dmhelp,f,indent=4)
                    orname = channel.name
                    await channel.edit(name = f"closed + {orname}")
                    delticket = discord.Embed(title="Support Team" , description = f"Your Ticket has been closed !!", color = 0x00c8ff)
                    await user.send(embed = delticket)
vale wing
#

Also json as a db is bad, you should learn about databases

primal token
#

love the blockingio

potent spear
radiant parrot
#

its works now thanks

glad cradle
#

i've a slash command parameter user_id: commands.Range[1, ...] = commands.Param(name="user_id", description="The member to unban") but discord says "enter a valid integer"

final walrus
#
mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Does somebody know why that happens when I run multiple instances of my command?

vocal snow
#

shouldn't you be using app_commands.Range

#

Range[int, 1, None]

vocal snow
#

and you should use aiomysql if you aren't already

final walrus
#

and I'm closing it

#

every time

vocal snow
#

why though

#

just connect once and use that throughout

#

could also consider a connection pool

final walrus
#

hmmm

silk fulcrum
#

Are Options possible in hybrid_commands? Like if I use it same as in an app command will it work for app command and if it works what will it be for a message command?

glad cradle
final walrus
silk fulcrum
glad cradle
#

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

slate swan
#

How to make welcome messages (nextcord)

slate swan
#

!d disnake.ext.commands.Range

unkempt canyonBOT
#

class disnake.ext.commands.Range```
Type depicting a limited range of allowed values.

See [Number Ranges](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-ranges) for more information.

New in version 2.4.
final walrus
slate swan
#

Hello, i keep getting this error

    return ctx.message.author.id == ctx.guild.owner.id
AttributeError: 'NoneType' object has no attribute 'id'
#

Guild.owner is None, you don't have member intents

#

!d

unkempt canyonBOT
torn sail
#

But it’s not really great for msg commands cause it doesn’t show the options

slate swan
#

!d

unkempt canyonBOT
shrewd apex
glad cradle
#

ids are too long to be integer in discord

#

really cringe

slate swan
quaint epoch
#

!black ?

slate swan
#

!pip black its a package

unkempt canyonBOT
glad cradle
slate swan
#

i see

#

so the issue was a long integer?

#

it will work if the table name and attributes given there are correct, and you provide Correct placeholder values while executing the query

#

syntax wise, its correct

glad cradle
#

I've type hinted as str

#

and converted as int in my code

stiff steeple
slate swan
#

whats the data type of number? you provide a string there

stiff steeple
#

anyone know whas wrtong

slate swan
stiff steeple
#

wdym

#

how do i fixc

bitter hill
#

hello am new to python and am trying to make a python bot that logs into my account and searches for channels in all guilds named "test" and posts a specific test if anyone can help me with that lmk pls

slate swan
#

you need to import modules before using them sir

slate swan
slate swan
#

you can use a bot for the same purpose

bitter hill
#

it'd take long to add the bot

#

to all the servers

slate swan
#

data type of the number column in your table?...

cerulean shale
#

yo how to get guild region? guild.region aint working

slate swan
#

you should have used INT or BIGINT for a numerical value

stiff steeple
#

what commands should I use bro

slate swan
#

and whats USERID? int or bigint? ( should ne BIGINT)

#

oh yes

cerulean shale
#

is my message invisible or something?

slate swan
#

that feature is deprecated

#

do you have the UPDATE rostercap in that query or not

#

and data type for GUILDID?

#

why don't you check it lol

glad cradle
slate swan
#

hello, my error keeps saying this.

error: TypeError: on_member_ban() missing 1 required positional argument: 'user'

@bot.event
async def on_member_ban(self, guild, user):
    with open('whitelist.json') as f:
        whitelisted = json.load(f)
        async for i in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.ban):
            if str(i.user.id) in whitelisted[str(guild.id)]:
                return
                await i.user.ban(reason="Azurite Antinuke | Banning Members.")
                return
glad cradle
unkempt canyonBOT
slate swan
#

yea, delete the table and recreate it witj new query

slate swan
glad cradle
slate swan
#

GUILDID should be the primary key with BIGINT data type
NUMBER should be INT or BIGINT

#

change the number variable to an integer

#

if its an argument, yes

#

what are the differences between discord.py and disnake?

#

UPDATE rostercap
SET NUMBER= %s
WHERE GUILDID = %s

slate swan
slate swan
#

eh write it inside a string

slate swan
#

like you did earlier

glad cradle
slate swan
#
TypeError: Messageable.send() got an unexpected keyword argument 'components'
slate swan
slate swan
#

why are you using the components kwarh then

slate swan
slate swan
slate swan
slate swan
slate swan
glad cradle
#

the bigger changes are in the ui kit

slate swan
glad cradle
kindred epoch
slate swan
#

What does this mean?

Desktop\VanityBot\bot.py:31: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```


**Code**:
```py
for filename in os.listdir('./cogs'):
  if filename.endswith('.py'):
    bot.load_extension(f'cogs.{filename[:-3]}')```
shrewd apex
slate swan
# shrewd apex await it

await bot.load_extension(f'cogs.{filename[:-3]}')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function

glad cradle
# slate swan await bot.load_extension(f'cogs.{filename[:-3]}') ^^^^^^^^^^^^^^^^^^^^^^^^^^...

A change in discord.py 2.0 made all methods related to extensions & cogs async.

Bot.load_extension(), Bot.unload_extension(), Bot.reload_extension(), Bot.add_cog(), and Bot.remove_cog are all coroutines now. This means you need to await them. Functions setup and teardown in extensions must be coroutines now. This means you need to define them with async def.

What is the purpose of this change?
It allows the setup and teardown functions of extensions to be coroutines.

async def setup(bot):
     await bot.add_cog(Commands(bot))

async def teardown(bot):
    return

View more:
Read more about the changes and how you can start your bot here: https://discordpy.readthedocs.io/en/latest/migrating.html#migrating-2-0-commands-extension-cog-async

#

Read the link

slate swan
#

so if i wanted to ad a cog, ill have to do them like this?

class MyBot(commands.Bot):
    async def setup_hook(self):
        await self.load_extension('f'cogs.{filename[:-3]}'')```
#

im so confused on this change.

slate swift
#
import discord
from discord.ext import commands

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

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

@client.event
async def on_ready():
    print("Ready")

@client.command()
async def hello(ctx):
    await ctx.send("Hello I am read Bot")

@client.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        await channel.connect()
    else:
        await ctx.send("You are not in a voice channel, join a voice channel to run this command!")


@client.command(pass_context = True)
async def leabe(ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send("I left the voice channel")
    else:
        await ctx.send("I am not in a voice channel")
#

can someone help^

glad cradle
slate swan
glad cradle
#

!pypi PyNaCl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

glad cradle
slate swan
silk fulcrum
#

thanks btw

pliant gulch
#

If the only thing your subclassing the bot for is setting setup_hook you can just use .event

#
bot = ...

@bot.event
async def setup_hook() -> None:
    ...

hollow rivet
#

In a discord embed, how do i add an hyperlink

slate swift
limber bison
#

how can my bot use emoji of different server in a different server
?

silk fulcrum
hollow rivet
#

Ah ok

#

Thanks

silk fulcrum
#

(works for diff servers too)

limber bison
silk fulcrum
limber bison
silk fulcrum
unkempt canyonBOT
silk fulcrum
#

I only remember dpy name

#

idk how it's called in discord

limber bison
silk fulcrum
#

i found, Use External Emojis

limber bison
silk fulcrum
#

wdym?

#

you need to enable it for bot

#

unless your bot has admin perms

limber bison
#

got it

#

thanksssss

slate swift
#
import discord
from discord.ext import commands

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

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

@client.event
async def on_ready():
    print("Ready")

@client.command()
async def hello(ctx):
    await ctx.send("Hello I am read Bot")

@client.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        await channel.connect()
    else:
        await ctx.send("You are not in a voice channel, join a voice channel to run this command!")


@client.command(pass_context = True)
async def leabe(ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send("I left the voice channel")
    else:
        await ctx.send("I am not in a voice channel")```
#

can someone help ^

silk fulcrum
#

pip install PyNaCl

slate swift
#

I did and it still doesnt work

silk fulcrum
#

wrong python version...

#

you installed it for python 3.9

#

and your bot uses 3.10

#

didnt you have that problem already?

slate swan
#

hello, this error is the same thing and i cant install aiofiles due to my school pc
how do i fix this?

@bot.event
async def on_guild_channel_create(self, channel):
    with open('whitelist.json') as f:
        whitelisted = json.load(f)
        async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_create):
            if str(i.user.id) in whitelisted[str(channel.guild.id)]:
                return
                await channel.guild.kick(i.user,reason="AntiNuke: Creating Channels")
                return```
slate swift
silk fulcrum
slate swan
slate swan
silk fulcrum
#

this is not in a cog

#

so remove it

silk fulcrum
# slate swift ? so what do i do..

C:\Users\dynam\AppData\Local\Programs\Python\Python310\python.exe -m pip install PyNaCl, there must be a better way, but im too tired, btw you could've remembered it yourself, cus you had this problem already

slate swift
#
async def leave(ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send("I left the voice channel")
    else:
        await ctx.send("I am not in a voice channel")```
#

anyone know why my leave command doesn't work the bot says "I am not in a voice channel" even tho it is

#

nvm it works

deep osprey
#
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
    with open("data.json", "a") as f:
        json.dump(channel.id,f)```how to make this code write channel id in a list because .json file looks like this ```json
112233```
idle laurel
#

when creating a slash subcommand is it possible to keep the main command function-able?

slate swan
#

In the title you can't, you can put an embed "author" though

silk fulcrum
slate swan
#

Or maybe it also works in title, it's just a different kwarg

mild lava
#

Master32 youre still here?

slate swan
#

Yeah makes sense that it works for both kek

silk fulcrum
#
emb = discord.Embed(title="Click me!", url="https://never-gonna-give-you-up.com/")```
silk fulcrum
mild lava
silk fulcrum
#

lmao

slate swan
#

delete that screenshot

deep osprey
#

hide ur token

primal token
#

Reset your token lol

mild lava
#

uh you just sent your token

slate swan
#

contains your token

rough moss
#

sryy

mild lava
#

go regenerate it and use environment variables

deep osprey
#

go reset it

mild lava
#

and next time send code not screenshot pls

primal token
#

either way it should be in an env file

slate swan
#

go on the developer portal and reset your token now, you never know if there are bots in this server etc.

rough moss
#

now its OK

deep osprey
#

reset it first

mild lava
primal token
#

watch the issue be the bot detects its own messages and cause recursion lol

hybrid fjord
#

how do i do this for multiple roles?

slate swan
#

Main problem for now is the light theme

rough moss
mild lava
#

whats with people sending screenshots

mild lava
# rough moss YE

alright, copy-paste the code here with formatting, then we can take a look

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

Better screenshots than sending code without formatting

rough moss
primal token
#

no

slate swan
#

We don't write for you

mild lava
silk fulcrum
slate swan
#

They guide you and help you figure out what's the issue

silk fulcrum
unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

primal token
hybrid fjord
mild lava
silk fulcrum
novel apexBOT
#

This is not a Modmail thread.

silk fulcrum
#

uh

primal token
#

:kek:

silk fulcrum
#

:lemao:

mild lava
#

@rough moss so, could you kindly paste the code here so i can read it?