#discord-bots

1 messages · Page 433 of 1

slate swan
#

but with this script he send it every time

unkempt canyonBOT
#

Hey @prisma wedge!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

prisma wedge
#

i cant send itr

slate swan
#

olso when the is a q

#

someone knows what to do?

timid beacon
#

tryguild.fetch_message() or client.fetch_message()

little ether
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.pydis.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.

prisma wedge
#

i saved it

#

what do i do now

wicked atlas
#

fetch_message is a method of a TextChannel object

prisma wedge
uncut comet
slate swan
#

How can I check a channel description to see if it includes a specific word?

little ether
prisma wedge
uncut comet
prisma wedge
#

is it that

#

yeah there

wicked atlas
slate swan
#

please?

timid beacon
wicked atlas
#

Ah wait, didn't read the whole message here

#

You might be able to just get the context object and use it

timid beacon
#

oh wait
is TextChannel.fetch_message()

wicked atlas
#

But @uncut comet, what are you trying to do?

prisma wedge
#

i have this code

#

how do i make the scroll menu work

potent otter
#

Hello all!

I have an issue where as a ' ' wont replace with '%20'. I'm fetching a span from a site, it works, but I need the command to work like >stats SEN TenZ 0001 and not >stats SEN%20TenZ 0001. I have to manually add the %20 for a space instead of a real one.

@client.command()
async def stats(ctx,username: str,tag: str):
  
  username.replace(" ", "%20")
  URL = f"https://tracker.gg/valorant/profile/riot/{username}%23{tag}/overview?playlist=competitive&season=all"
  URL2 = f"https://tracker.gg/valorant/profile/riot/{username}%23{tag}/overview?playlist=competitive"
  if ' ' in username:
    username.replace(" ", "%20")
  page = requests.get(URL, URL2)
  soup = BeautifulSoup(page.content,"html.parser")
  results = soup.find("span", {"class":"valorant-highlighted-stat__value"})
  rank = results.text
lunar helm
#

ok so

#
async def check_role(user, level, plus):
    with open('roles.json', 'r') as f:
        roles = json.load(f)
    for i in range(len(roles)):
        if not roles[str(level)]:
            print(f"no role for level {i}")
        else:
            await user.add_roles(roles[str(level)])```
#

this is supposed to auto role on level up

#

but it causes a loop

#
async def level_up(users, user, channel, server):
  experience = users[str(user.guild.id)][str(user.id)]['experience']
  level_start = users[str(user.guild.id)][str(user.id)]['level']
  level_end = 25 * (2 * (level_start+1)**2 + (level_start+1))
  if str(user.guild.id) != '757383943116030074':
      print(experience)
      print(level_end)
      if int(experience) >= int(level_end):
          await channel.send('{} has leveled up to Level {}'.format(user.mention, level_start+1))
          users[str(user.guild.id)][str(user.id)]['level'] = level_start+1
          plus = True
          await check_role(user, level_start+1, plus)```
#

and commands stop working

lost fossil
#

im trying to make an embedder but i cant figure out how can i separate the title from the msg

@client.command()
async def update(ctx, *, title, msg):
    embed = discord.Embed(title=f"**{title}**", description=f"{msg}", color = 0xFFFF00)
    await ctx.send(embed=embed)
    await asyncio.sleep(0.1)
    await ctx.message.delete()
potent otter
lost fossil
#

if i just do
*update <title> <msg>

#

it will miss the msg and put it as a title

patent lark
#

id assume the whole argument is taken as the title, according to how their parameters are set up.

lost fossil
#

so what can i do to separate the title and the msg

verbal hill
#

this doesnt work so im still confused
end = datetime.utcnow()+timedelta(seconds=tr).total_seconds()

wicked atlas
verbal hill
#

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'float'

wicked atlas
#

Ah, well, that's because you are doing total_seconds() from the timedelta, and trying to subtract it from the datetime

#

you need to do it from the product of the two

end = (datetime.utcnow()+timedelta(seconds=tr)).total_seconds()
verbal hill
#

let me try that

#

is there something i need to import at the top of my code btw @wicked atlas?
Command raised an exception: AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

slate swan
#

i know that one?

#

How do I get a specific word from a list?

#

maybe

#

Like a bad word from a bad word list

#

i try like an hour

#

or someone

#

pls

wicked atlas
#

forgot that total_seconds was a timedelta thing

slate swan
#

Is there a pallet site with Hex numbers for dpy?

#

bcs i couldnt find anythign

wicked atlas
#

@verbal hill just do .timestamp() instead

slate swan
wicked atlas
unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)").

There is an alias for this called Color.

`x == y` Checks if two colours are equal.

`x != y` Checks if two colours are not equal.

`hash(x)` Return the colour’s hash.

`str(x)` Returns the hex format for the colour.
slate swan
#

but customizable

wicked atlas
verbal hill
wicked atlas
#

Just put that into format for discord

#
<t:1630368639>
#

Which will come out as <t:1630368639>

#

ok, can't have the decimal apparently

lunar helm
#
await user.add_roles(roles[str(level)], reason="leveled up", atomic=False)```
#

AttributeError: 'int' object has no attribute 'id'

#

{"2": 881581831814799420}

verbal hill
wicked atlas
#

Use an f-string

#
f"<t:{end:.0f}>"
verbal hill
#

ah the way i tried it didnt work

#

i tried f"{<t:end2>}"

#

lol

wicked atlas
#

You might need to convert it to an integer, so you don't have the decimal at the end

lunar helm
#

i found my problem

#

how do i make a role object using just a role id

wicked atlas
lunar helm
#

ok

#

thx

#

btw

lost fossil
forest vortex
final iron
#

I'm making an embed and in the author part how would I put their pfp

    @commands.command(aliases=['av'])
    async def avatar(self, ctx, *, member: discord.Member=None):
        if not member:
            member = ctx.message.author

        embed=discord.Embed(title="**Avatar Command**",
                            description="Returns with avatar of a user or yourself",
                            color=0xff0000)
        embed.set_author(name=f"{member}" )

        await ctx.send(embed = embed)
patent lark
#

icon_url=ctx.author.avatar_url

final iron
#

I can't get the url tho

#

Cause the code wont embed into an image in an embed

patent lark
#

what?

final iron
#

This is what I have so far

#

To the right of my name I would like to have the users pfp

patent lark
#

member.avatar_url

#

use the icon_url kwarg in set_author

slate swan
#

Heyho! I want to get all existing channel permissions in a list without having to type them out manually. Is that possible?

#

Like manage_channel and so on

patent lark
#

so embed.set_thumbnail(url = member.avatar_url)

sinful marsh
#
import discord
from discord.ext import commands
import asyncio
import json
import os
import traceback
import logging
import sys




#Discord client constructor
intents = discord.Intents.default()
client = commands.Bot(command_prefix=json.load(open('./config.json', 'r'))['Prefix'], intents=intents)
client.remove_command('help')
    
#Setup Discordpy Warning Logging
dpylogger = logging.getLogger('discord')
dpylogger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='./logs/dpylogger.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
    
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.WARNING)
streamhandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s -  %(message)s'))
    
dpylogger.addHandler(handler)
dpylogger.addHandler(streamhandler)
    
# Setup Main Python Logging
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
    
mainfilehandler = logging.FileHandler(filename='./logs/mainlogger.log', encoding='utf-8', mode='w')
mainfilehandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
    
strhandler = logging.StreamHandler()
strhandler.setLevel(logging.INFO)
strhandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
    
logger.info('Loading Cogs')
    
    #Load Cogs 
for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        try:
            client.load_extension(f'cogs.{filename[:-3]}')
        except (ImportError, SyntaxError) as e:
            logger.fatal(f'Failed to load extension {filename}')
            traceback.print_exc(e)
            sys.exit(1)
    
    
    

if __name__ == '__main__':
    try:
        client.run(json.load(open('./config.json', 'r'))['Token'])
        
    except discord.HTTPException:
        logger.fatal(f'HTTPException in main loop')
        sys.exit(1)
    except discord.LoginFailure as lf:
        logger.fatal(f'LoginFailure in main loop')
        logger.fatal(lf)
        sys.exit(1)
``` Am is missing somthing? The logger calls are not working at all, neither are the ones inside my cogs. Is there a special syntax for using logging in cogs?
final iron
#

ty

slate swan
sinful marsh
#

Anyone lol? im pulling my hair out

final iron
#

I've ran into another issue

#

The url wont embed into a gif

slate swan
#

There was a way to make links a file uhhhm

final iron
#

I just want it to embed into a gif

slate swan
#

I remember I had problems with putting a gif into an embed too so

#

Oh- right sry xd

final iron
#

If anyone knows can they ping me

#

my code is

    @commands.command(aliases=['av'])
    async def avatar(self, ctx, *, member: discord.Member=None):
        if not member:
            member = ctx.message.author

        embed=discord.Embed(title="**Avatar Command**",
                            description=f"Returns with avatar of a user or yourself.\n\n**Avatar Of**\n`{member}`\n\n{member.avatar_url}",
                            color=0xff0000)
        embed.set_author(name=f"{member}" )

        await ctx.send(embed = embed)
#

Also quick question

#

Is it possible to remove the default help command

#

And another question

#

In the brackets in the async def line what does the * do

slate swan
slate swan
final iron
slate swan
#

If you mean
async def hello(ctx,*,abc)

#

Well if someone gives multiple arguments like

#

Hello I am cool

#

if you only type (ctx,abc), abc would be "Hello", but since theres a * it will be "Hello I am cool" or if there are more arguments (ctx,hello,*,rest)
It would be "I am cool"

final iron
#

thats a bit confusing

slate swan
#

Welp thats how it is

#

Imagine you want to make a...very simple example... !say command, now letting the user do !say hello would give "hello", but if they type !say hello world, itll still be "hello"

#

Thats why * comes in game

final iron
#

ah

slate swan
#

Very handy

#

Yep

slate swan
#

That would make it shorter, just a hint

maiden fable
#

Second one works yes

final iron
#

Yes it does thank you

slate swan
#

Np

final iron
#

Im still tryna figure out how to the the pfp in the top left of the embed

slate swan
#

OHHGG

#

Wait it was...

final iron
#

?

maiden fable
unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
slate swan
#

yea uff you were faster

maiden fable
#

(:

slate swan
#

¯\_(ツ)_/¯

final iron
#

this is what I tried doing

#
embed.set_author(name=discord.Embed.set_thumbnail(self, url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024'))
maiden fable
#

Ah, that's now how u do it

#
embed.set_thumbnail(url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024')
final iron
#

That wasn't what I was really looking for

maiden fable
#

Then?

final iron
#

I was looking for something like this

#

In the top left theres a little pfp

maiden fable
#

Ah

#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
final iron
#

Like what would I put there

maiden fable
#

U can ignore that. Just put in your icon url in icon_url :)

final iron
#

That works ty!

maiden fable
#

Cool

final iron
#

Any idea how to get my url to embed into an image?

#

It wont embed into a gif

maiden fable
#

Code

final iron
#
    @commands.command(aliases=['av'])
    async def avatar(self, ctx, *, member: discord.Member=None):
        member = member or ctx.message.author

        embed=discord.Embed(title="**Avatar Command**",
                            description=f"Returns with avatar of a user or yourself.\n\n**Avatar Of**\n`{member}`\n\n{member.avatar_url}",
                            color=0xff0000)

        embed.set_author(name=f'{member}', icon_url='https://cdn.discordapp.com/avatars/669343267589980160/a_c431e2fde24c6136f7c5fac789057227.gif?size=1024')
        embed.set_footer(text="")
        await ctx.send(embed = embed)
maiden fable
#

Weird

#

Ah

#

I think you can't have both, text and a link in the description

final iron
#

Alright

lofty heron
#

hi how can i make an alias for a command? i've looked through the docs but i don't understand noob

maiden fable
#

Add them inside the list brackets

lofty heron
#

hmm how would i do that for a particular command?

maiden fable
#

I just told you that....?

stoic whale
#

how do I make only one button work for a role?

lofty heron
#

oh nvm kek

maiden fable
patent lark
#

now p and pong would trigger this command

maiden fable
final iron
#

Yeah I seriously have no idea how to get the url to embed into an image

patent lark
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
patent lark
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
maiden fable
unkempt canyonBOT
#

set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
maiden fable
#

(:

patent lark
unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
maiden fable
visual island
#

umm, why is this thing typing for so long...

final iron
maiden fable
#

Cz the person is typing for too long? @visual island

final iron
#

I finally made my avatar command and imo it looks pretty good

visual island
maiden fable
# visual island its... a bot

Ah, seems like a discord bug.. If it's yours, then restart it. I remember someone telling me that there is a bug in ctx.typing

#

Idk if it was fixed or not tho

patent lark
#

ctx.trigger_typing() ?

maiden fable
patent lark
#

cant you also use like uh

maiden fable
#

?

#

async with?

patent lark
#

ctx.channel.typing?

maiden fable
#

breh, it's the same....

patent lark
#

i know

visual island
#

yeah i did async with args[0].typing():

#

bruh the indent

maiden fable
#

abc.Messageable is the base class

#

!d discord.abc.Messageable.trigger_typing

unkempt canyonBOT
#

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

Triggers a *typing* indicator to the destination.

*Typing* indicator will go away after 10 seconds, or after a message is sent.
maiden fable
#

There

#

But that should have stopped after 10 seconds

visual island
#

1 sec

maiden fable
#

@visual island do u have an eval? If yes, then try sending a message with the eval. Should stop after that

wheat ember
visual island
slate swan
#

did you imported the libraries for slash commands@wheat ember

maiden fable
#

Weird

maiden fable
#

Mhm

slate swan
#

@wheat ember did you define it?

wheat ember
slate swan
#

just like you do

visual island
maiden fable
#

Lmao

slate swan
#

Bot = commands.Bot() there must be something for your slash library too

maiden fable
#

Restart the bot

visual island
maiden fable
#

7408_shrekstare this pro just failed

visual island
#

but how

#

to

maiden fable
maiden fable
#

Seems like the bug still exists. I'mma see if I can find the root cause of it (possibly won't be able to find it but who knows)

lofty heron
#

hi does anybody know how the colours for embeds work? what colour format is it in?

maiden fable
#

Or u sure a command wasn't getting executed?

lofty heron
#

tenks

maiden fable
#

Just prefix 0x

lofty heron
#

ok

#

me extra confoooos because 0x prefix lel

maiden fable
#

Ah

#

Well it's just Python's way to display colors

#

0xhex-code

wheat ember
slate swan
#

@wheat ember just go to their docs

#

and have a look around

wheat ember
visual island
#

not really, @unkempt canyon does that also

daring lotus
#

whenever i try to run my bot I get this

raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
#

Anyone know why?

#

should be lemme check

#

IT WAS OFF BY A SPACE

#

THX

exotic patrol
#

Do:

@commands.has_any_role(id1, id2....)```
#

can put up ad many ids as you want

wheat ember
#

can some one type a work slash command example???

exotic patrol
#

do

@commands.has_any_roles(id1, id2...)```
slate swan
#

Remove the ...

#

well

#

You need to use if and else then

#

@slate swan

patent lark
#

no

#

you are incorrect

#

its @commands.has_any_role()

slate swan
#

oh

patent lark
#

you can put many ids

#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
patent lark
#

i see

#

if you use an ID it should be an int not str

#

but a role name must be a str

#

let me see your code

#

that should work fine

#

send your full traceback error

#

i see

#

on_command_error eats errors

#

what does it tell you?

hoary gust
#
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 103, in remove_warn
    test = r.orders.find({"guild": ctx.guild.id, "member": member.id}).sort( { "warn": -1 } )
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
    cursor_method(self.delegate, *args, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list```



@patent lark plz help
velvet yarrow
#
hey can anyone help me i want to test my bot
if you can join my server DM me
you can leave after testing```
subtle glen
#

Guy!!! wat happend to me?

maiden fable
#

U need to use commands.Bot

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

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

is there a method for stopping the Context.typing()? Cause it seems that using context manager triggers the typing forever...

maiden fable
#

No

visual island
#

sad

subtle glen
maiden fable
#

No

subtle glen
lament ridge
lament ridge
#

what

#

async_timeout

visual island
#

a lib?

lament ridge
#

ye

hoary gust
#

@maiden fable bud can u help me regarding mongo

visual island
lament ridge
#

what about asyncio.wait_for?

visual island
#

it probably behaves the same as async_timeout. no?

lament ridge
#

not really, no

maiden fable
maiden fable
#

Cya!

hoary gust
#

honestly the whole server is full of sql users no mongo user but why

lament ridge
#

mongo = bad

#

thats why

maiden fable
#

Breh

hoary gust
lament ridge
#

MongoDB is a NoSQL database that stores data as documents in BSON format. Not recommended in general as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.

hoary gust
#
Ignoring exception in command remove_warn:
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 102, in remove_warn
    test = r.find({}, {"guild": ctx.guild.id, "member": member.id}).sort( { "warn": -1 } )
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
    cursor_method(self.delegate, *args, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list

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

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: if no direction is specified, key_or_list must be an instance of list

Process finished with exit code -1

someone help

patent lark
#

mongo is not bad , it’s not recommendable for certain things, this brings back the JSON discussion, how everyone says JSON is bad, no, json is not bad, it’s just not supposed to be used for database purposes. same with mongo, it’s a database with pros and cons to certain things

hoary gust
#

@patent lark can u help me with mongo

lament ridge
#

imma head back to dpy server ill ttyl

#
avatar_url_as('png', size=4096).url```
subtle glen
#

help me ;-;

#

i dunno how to fix

slim linden
#

send code

empty hearth
#

Why does this channel still exist

#

I’ll miss it

dapper cobalt
# subtle glen help me ;-;

You don't have message defined anywhere. And also that's an on_member_join event, which its parameters are member and self if you are using cogs. If you want to send a message to a channel then get the channel with bot.get_channel(channel id) then send the message to the channel object that returns.

subtle glen
#

oh

dapper cobalt
visual island
dapper cobalt
#

^

maiden fable
empty hearth
dapper cobalt
#

General discord bot development in python support.

maiden fable
visual island
empty hearth
#

Are they even good…

dapper cobalt
maiden fable
unkempt canyonBOT
dapper cobalt
maiden fable
empty hearth
#

JS users are mocking us rn..

maiden fable
maiden fable
visual island
#

maybe later, cause im not really know aiohttp too much

#

and typing stuffs

maiden fable
#

Ah

#

Understandable

empty hearth
#

xd

maiden fable
cunning fiber
#

why does @commands.has_permissions() raise the MissionPermissions exception even though the member has a role that grants the specified permission check?

maiden fable
maiden fable
unkempt canyonBOT
#

discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").

New in version 1.3.
cunning fiber
#

thanks for the alternative

maiden fable
#

(:

hoary gust
#

@maiden fable

maiden fable
#

Yea

hoary gust
#

can u help me now

#

plz

maiden fable
#

Also, about the mongo thing. I haven't really used it, but u can also try asking in #databases (but go on, post the question here also)

hoary gust
maiden fable
#

Haha

#

May I know the error?

wheat ember
#

How do I define parameters to include or not?

hoary gust
# maiden fable May I know the error?
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 102, in remove_warn
    test = r.find({}, {"guild": ctx.guild.id, "member": member.id}).sort({"warn", -1})
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\motor\metaprogramming.py", line 272, in return_clone
    cursor_method(self.delegate, *args, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\cursor.py", line 726, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\helpers.py", line 73, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list

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

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: if no direction is specified, key_or_list must be an instance of list
#

@maiden fable ^

hoary gust
maiden fable
#

Same

hoary gust
#

dict direction

maiden fable
#

Breh

hoary gust
maiden fable
#

Try seeing this

hoary gust
#

now i am getting ```AsyncIOMotorCursor(<pymongo.cursor.Cursor object at 0x0000026991699190>)

#

@maiden fable

#

need help

#
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 103, in remove_warn
    fin = test["warn"]
TypeError: 'AsyncIOMotorCursor' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'AsyncIOMotorCursor' object is not subscriptable

i want to get the descended value from warn in my mongodb but how can i get that descended value now

tight obsidian
#

Please don't ping random people for help. I know absolutely nothing about mongo. If you have a question about databases, post in #databases, not in this channel.

hoary gust
velvet yarrow
#

Hey can any one help me in testing of my bot?

slate swan
velvet yarrow
slate swan
#

Oh.. uh

#

You don't have anyone else, a friend or an alternative account to test?

velvet yarrow
#

one of member is afk they not responding

silver wolf
#

Then make an alt account?

slate swan
#

I mean thats the best thing to do to test tbh

lofty heron
#

hi does anybody know how to make a footer for an embed? idk how and i'm kinda confused

slate swan
#

Yeah

lofty heron
#

hmm oop never mind

#

just didn't have a comma

slate swan
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
lofty heron
#

yee

velvet yarrow
#

thanks

maiden fable
hoary gust
maiden fable
#

That happens when u didn't call a function in yr code

hoary gust
maiden fable
#

Idk, never used mongo

elfin island
maiden fable
#

Ah, I think thTs the problem

elfin island
#

you should read it

tight obsidian
#

In the discord API, what is a "partial" object? I wasn't able to find the definition anywhere.

lucid stream
#

anand im not able to login through my discord bot client is it put down for violating terms or something

maiden fable
#

Same with PartialEmoji. It's an emoji from a guild the bot isn't the part of

tight obsidian
#

But what is its structure? What fields does it have etc.?

maiden fable
#

!d discord.PartialMessage

unkempt canyonBOT
#

class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via [`TextChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.get_partial_message "discord.TextChannel.get_partial_message") or [`DMChannel.get_partial_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.DMChannel.get_partial_message "discord.DMChannel.get_partial_message").

Note that this class is trimmed down and has no rich attributes.

New in version 1.6...
tight obsidian
#

I'm not talking about discord.py, just the API definition

maiden fable
#

Ah

#

Well, I don't know much about that, sorry :c

slate swan
#

afaik partials are just a way to still create the objects when the bot doesnt receive enough information

#

and they are a library only thing

maiden fable
#

Yea

tight obsidian
slate swan
#

oh

maiden fable
#

Weird

slate swan
#

then dont listen to me, I may have misread something

maiden fable
#

Tbh, I also didn't really understood the Partial objects, and I like to use the proper objects like discord.Message

slate swan
#

I dont think you are really supposed to use them normally anyways, since they lack most important data the object should have. Unless you are doing something tricky, hacky or wacky

wind tangle
#

can anyone help me with this

#
import os
import discord
import os
# load our local env so we dont have the token in public
from dotenv import load_dotenv
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from discord import TextChannel
from youtube_dl import YoutubeDL

load_dotenv()
client = commands.Bot(command_prefix='.')  # prefix our commands with '.'

players = {}


@client.event  # check if bot is ready
async def on_ready():
    print('Bot online')


# command for bot to join the channel of the user, if the bot has already joined and is in a different channel, it will move to the channel the user is in
@client.command()
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()


# command to play sound from a youtube URL
@client.command()
async def play(ctx, url):
    YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
    FFMPEG_OPTIONS = {
        'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    voice = get(client.voice_clients, guild=ctx.guild)

    if not voice.is_playing():
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
        URL = info['url']
        voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
        voice.is_playing()
        await ctx.send('Bot is playing')

# check if the bot is already playing
    else:
        await ctx.send("Bot is already playing")
        return


# command to resume voice if it is paused
@client.command()
async def resume(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if not voice.is_playing():
        voice.resume()
        await ctx.send('Bot is resuming')


# command to pause voice if it is playing
@client.command()
async def pause(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice.is_playing():
        voice.pause()
        await ctx.send('Bot has been paused')


# command to stop voice
@client.command()
async def stop(ctx):
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice.is_playing():
        voice.stop()
        await ctx.send('Stopping...')


# command to clear channel messages
@client.command()
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)
    await ctx.send("Messages have been cleared")
#

nothing except.help works

serene lynx
#
raised an error: ExtensionFailed: Extension 'cogs.love' raised an error: OSError: cannot open resource```
#

does anyone know what is the cause of this?

visual island
unkempt canyonBOT
#

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

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

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

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

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

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
serene lynx
serene lynx
unkempt canyonBOT
#
Huh? No.

No documentation found for the requested symbol.

serene lynx
#

I don't think so, it only sends images via bytesio

#

maybe open files from bytesio

#

but it runs on a normal local, no errors

fair axle
#

is the module dislash safe?
i want to create context menus

#

so what are the dependencies if there are any

hearty olive
#

hello, can someone help, is discord.py only used for discord bots?

#

or you can do some basic tasks with it to

#

lets say just type some message i tell it to type, in some server or dm

#

oh it has to work with the bot?

#

what i meant is if discord.py can kind of do some tasks on my account,

#

ah, i see

#

what about logging in

#

i give it username or password or maybe my token and it logs me in, is that technically possible

hearty olive
#

aight, I'II try that stuff out

open brook
#

I warn not to do that

#

It is against discord tos

hearty olive
#

oh, not even that?

#

aight well lol guess i will find another project to work with, cause i dont think i will be able to make bots cause iam pretty new

unkempt canyonBOT
#

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

open brook
#

I didn't know that lol

#

Alright

hearty olive
#

gotcha, i didnt know that was again tos, thanks for the help tho

open brook
#

But then I gave a disclaimer

#

Okay what is the best way to make a music bot?

hearty olive
#

i think you said that about sending message not logging in, just for the record iam new to python and modules specificly so was just trying to learn

open brook
#

Ya ik

#

Not with ytdl

#

Any other way

hearty olive
#

aight cya!

vale glen
#

is it possible to use a for loop and look through all messages in a channel

vale glen
open brook
#

Spotify api?

#

You can't log messages of a server

#

Finding specific msg is fine

vale glen
#

it was to check how many msgs u've sent in a channel

wind tangle
#

help me with this someone

#

why is this chat so active

vale glen
#

i dont think u need to import discord.utils

#

i think it comes with import discord

wind tangle
#

ok thank

vale glen
#

what is discordutils.music

wind tangle
vale glen
#

uhh idk

#

i dont do music bot

rain bolt
#

Traceback (most recent call last):
File "F:\python project\webhookbot.py", line 1, in <module>
from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'

Process finished with exit code 1

#

pls help me to eror cmd

vale glen
#

???

#

pld ep to eror cmd?

#

oh

velvet yarrow
#

any one who can help me with aiosqlite3

unkempt canyonBOT
#

@rain bolt, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

rain bolt
#

my code

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

rain bolt
#

webhook = DiscordWebhook(url='', content='Sykhob ast \n @here')
response = webhook.execute()```
#

?

#

Traceback (most recent call last):
File "F:\python project\webhookbot.py", line 1, in <module>
from discord_webhook import DiscordWebhook
ModuleNotFoundError: No module named 'discord_webhook'

Process finished with exit code 1

#

eror

#

:||

#

tnx

serene lynx
serene lynx
vale glen
#

k

#

i dont make music bots so idk

upper plover
#

guys i have level system how to add to him role reward example: Every level up = role

slate swan
#

i have on_guild_join event that changes voice channel name, in on guild remove im tryna get it too do that same thing but it doesnt change the channel name at all...

@bot.listen("on_guild_remove")
async def remove(guild):
    voice = bot.get_channel(881797481694900225)
    await voice.edit(name=f"Guilds: {len(bot.guilds)}")```
slate swan
#

nope

grim oar
#

The Id is valid?

round raptor
#

?play jghuioh 865863610903166976

#

not working pls help

grim oar
#

you need an instance of discord.VoiceChannel, you have it as vc so use .connect() method on it

round raptor
#

is this ok

grim oar
#

await vc.connect()

round raptor
#

ok

slate swan
vale pendant
grim oar
round raptor
grim oar
#

If you mean command then, Like how you normally do it,
prefixplay url channel

vale pendant
# slate swan yh

and if you want it to tell you how much guilds it’s in, make a task loop.

round raptor
vale pendant
#

or just length it - 1

grim oar
vale pendant
vale pendant
round raptor
grim oar
#

Any error

round raptor
#

no error

grim oar
#

ahh I didn't see, you are using name instead of id in utils.get

agile goblet
#

just typehint the channel argument

grim oar
#

^

visual island
#
def send_typing(seconds=3):
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            args[0].bot.loop.create_task(asyncio.wait_for(args[0].typing(), timeout=seconds))
            await func(*args, **kwargs)
        return wrapper
    return decorator

```seems that it did not trigger the typing?
grim oar
#

typehint channel to discord.VoiceChannel as nubz said and then await channel.connect()

visual island
# visual island ```py def send_typing(seconds=3): def decorator(func): @functools.wr...

so i changed the code a bit

def send_typing(seconds=3):
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            with args[0].typing():
                print("hi2")
                await func(*args, **kwargs)
                print("hi3")
            print("hi")
        return wrapper
    return decorator

```hi3 and hi was never printed... probably the `await func(*args, **kwargs)` blocks the context manager?
floral crypt
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "881503416436805642>'" is not snowflake.
#

How to get the emoji id out of a message

raw escarp
#

pls help🙏

slate swan
grim oar
#

^

visual island
#

i see

#

i think i should create it as a task then

grim oar
#

It will still block tho (if you try getting the result there)

karmic nymph
#

I have a list index of i which represents my level

#

how do I find all the other levels

#

I want to remove all the other roles on the user so his level roles dont stack

glad stratus
#

How to make bot reaction to its own message, and when you click on this reaction, it must do an event?

floral crypt
#

How can i get a id of an emote

#

out of a message

#
                mensaje3 = await ctx.send('¿Con qué emote reacciono? Escribe `cancelar` para salir.')
                eliminar.append(mensaje3)
                message3 = await bot.wait_for('message', check=check)
                eliminar.append(message3)

                if message3.content.lower() == 'cancelar':
                    await borrar_msgs(eliminar)
                    await ctx.send('Comando cancelado.', delete_after=3)
                    return

                else:
                    emoticono = f"{int(message3.content)}"
                    await mensaje_reaccion.add_reaction(emoticono)```
#

this error

#
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "881503416436805642>'" is not snowflake.
slate swan
unkempt canyonBOT
#

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

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

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

hey bud

reef dock
hoary gust
#

!yt

unkempt canyonBOT
#

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

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

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

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

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

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

oh ya

hoary gust
#

@gloomy coral btw i need a bit help

gloomy coral
#

i hate my life

#

speak

#

ill try to

hoary gust
# unkempt canyon

in member.add_roles am i supposed to get the id or can directly use the name

floral crypt
#

Someone

#

Please

pale turtle
#

You need the Role object

hoary gust
pale turtle
#
role = member.guild.get_role(role_id)
await member.add_roles(role)```
gloomy coral
#

use getrole

#

then addrole
there

pale turtle
#

Maybe an id will also be enough, but not sure

hoary gust
#

??

pale turtle
hoary gust
pale turtle
#

You'd need to use discord.utils.get

hoary gust
#

like instead of id i will use its name

pale turtle
maiden fable
#

@pale turtle u still gonna make bots?

#

😂

hoary gust
#

@maiden fable

#

hey hunter can u plz tell me how can i make a loop

#

except while loop

agile goblet
#

like;

try:
    ...
except:
    while:
        ...

?

#

or what

hoary gust
dim wing
#

is it possible to add buttons with discordpy lib?

lament mesa
#

yes, you can use v2

dim wing
#

how to install v2?

slate swan
#

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

dim wing
#

mmh okay

hoary gust
#

@slate swan sry for ping but i have a question that if i ban a user so will it execute the on_member_remove event or i need to use on_member_ban

dim wing
#

and if i use python3 -m pip install -U discord.py it installs wich version?

dim wing
#

okay thx

slate swan
dim wing
#

but does the discordpy doc supports the v2?

slate swan
#

_ban

hoary gust
#

ok

lament mesa
#

both?

hoary gust
#

but doesnt it require the guild param

slate swan
hoary gust
#

^

lament mesa
#

!d discord.on_member_ban

unkempt canyonBOT
#

discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").

This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
lament mesa
#

guild and user

slate swan
# lament mesa both?

I think the first one is when member itself left or gets kicked rooThink Also the latter one returns a user and guild object rather than member like in the former

dim wing
#

last question ^^: is latest the same as master?

lament mesa
slate swan
slate swan
lament mesa
#

ig so

#

never banned anyone in my server

lament mesa
slate swan
minor kestrel
#

What is occuring with discord.py?

What do I need to do for my bot to continue working?

lament mesa
#

dpy will work

minor kestrel
#

ok thx

reef dock
#

after modifying a slash command option type i have to wait upto an hour for those changes to apply correct?

hoary gust
#

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

minor kestrel
hoary gust
#
pun is not none
Ignoring exception in command warn:
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\USER\Desktop\ZENESIS DEVELOPEMENT\PYTHON\ZENESIS\WARN SYSTEM [MONGO]\commands\warn.py", line 108, in warn
    punish = pool["punishment"]
TypeError: '_asyncio.Future' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_asyncio.Future' object is not subscriptable```
vocal plover
hoary gust
#
pool = p.find_one({"guild": ctx.guild.id})
            print(pool)```

i am getting the error at this line
vocal plover
#

you need to await it

minor kestrel
vocal plover
#

p.find_one, that is

minor kestrel
#

what does that means?

hoary gust
vocal plover
hoary gust
minor kestrel
vocal plover
#

many

lament mesa
high flame
#

ofc there should be some

brisk helm
#
async def lvl_top(self,ctx,page=0):
    db = sqlite3.connect("lvl.db")
    curosor = db.cursor()


    current = 1
    index = 1
    member_per_page = 3

    embed = discord.Embed(title=f"{page}",description=f"")
    msg = await ctx.send(embed=embed)

    while True:
        if current != page:
            embed.title = f"{page}"
            embed.description = f""
            curosor.execute("SELECT member_id,exp, lvl FROM lvl WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ?", (ctx.guild.id,member_per_page,page,))
            index = member_per_page*(current-1)
            wynik = curosor.fetchall()

            for entry in wynik:
                index += 1
                member_id = entry[0]
                exp = entry[1]
                member = ctx.guild.get_member(member_id)
                embed.description += f"{index}) {member.mention} - {exp}\n"
            await msg.edit(embed=embed)``` Whi it only reacts only for first command
#

and why in 1 page no one is but on next they are

#

<object Rush2618 at 0x001B561E0> can you help??

subtle kelp
#

don't connect to the db every time a command in invoked

brisk helm
subtle kelp
#

i am not sure sorry

dapper cobalt
# brisk helm ```py async def lvl_top(self,ctx,page=0): db = sqlite3.connect("lvl.db") ...

You don't have to make your own pages, you can paginate it in another way.

from discord.ext.buttons import Paginator


class Pag(Paginator):
    async def teardown(self):
        try:
            await self.page.clear_reactions()
        except discord.HTTPException:
            pass

class SomeClass(commands.Cog):

  @commands.command()
  async def page_names(self, ctx, names:list):
    pager = Pag(
      timeout=3600, # how much it takes for the buttons to time out
      entries=names, # the array that you want to be paginated
      length=20, # how many items in a single page
      prefix="",
      suffix=""
    )
    await pager.start(ctx)
brisk helm
brisk helm
brisk helm
dapper cobalt
#

It just gives easier use.

gloomy coral
#
@commands.command(aliases=["gi","googleimages","image"])
    async def googleimage(self, ctx, num:int,*imaged):
        await ctx.send("This might take a few seconds")
        
        q = " ".join(imaged)
        start = 1
        _search_params = {
            'q': q,
            'searchType': 'image',
            'num': num,
            'start': start,
            'safe': 'medium',
            'fileType': 'jpg',
            'imgType': None,
            'imgSize': None,
            'imgDominantColor': None
        }
        gis.search(self,search_params=_search_params, path_to_dir='\images')
        count = 1
        dirrr = "\images"
        for file in os.listdir(dirrr):
            if file.endswith(".jpg"):
                os.rename(f".\images\{file}",
                          f".\images\image{count}.jpg")
                count += 1
        for image in os.listdir('.\images'):
            if image.startswith("image"):
                await ctx.send(file=discord.File(f'\images\{image}'))```
#

This wont work

#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/chad-the-discord-bot/cogs/info.py", line 244, in googleimage
    gis.search(self,search_params=_search_params, path_to_dir='\images')
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/google_images_search/fetch_resize_save.py", line 125, in search
    if not self._search_again:
AttributeError: 'Info' object has no attribute '_search_again'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Info' object has no attribute '_search_again'```
gloomy coral
#

from google_images_search import GoogleImagesSearch as gis

dapper cobalt
#

I'm not sure but I believe that this is a bug with the library you are using.

#

Try removing self from gis.search().

gloomy coral
#

it shows error

slate swan
#

need help please

#

for auto rôle

dapper cobalt
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

dapper cobalt
#

No such thing.

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

`x == y` Checks if two guilds are equal.

`x != y` Checks if two guilds are not equal.

`hash(x)` Returns the guild’s hash.

`str(x)` Returns the guild’s name.
slate swan
#

ok so let's try change it

dapper cobalt
#

member.guild not discord.Guild.

slate swan
#

like that ?

dapper cobalt
#

And I suggest you don't put the id in a string.

dapper cobalt
agile goblet
#

id is always an int

slate swan
#

ok thanks

agile goblet
#

also

#

its member.add_roles(role)

slate swan
#

ok, thanks and let try

upbeat otter
#

Guys, i want to make a leaderboard feature, which tells the top 3 active users of the server of the past 3 days, any idea how can i do that?

#

umm?

dapper cobalt
unkempt canyonBOT
upbeat otter
upbeat otter
dapper cobalt
#

No problem.

brisk helm
# dapper cobalt 2 of them are to go back and forward one by one, 2 of them are to go back and fo...
async def lvl_top(self,ctx):
    db = sqlite3.connect("lvl.db")
    curosor = db.cursor()

    page = 0
    current = 1
    index = 1
    member_per_page = 3
    emojis = ["⬅️","➡️"]
    embed = discord.Embed(title=f"{current}",description=f"")
    msg = await ctx.send(embed=embed)

    await msg.add_reaction("⬅️")
    await msg.add_reaction("➡️")
    while True:
        if current != page:
            embed.title = f"{current}"
            embed.description = f""
            curosor.execute("SELECT member_id,exp, lvl FROM lvl WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ?", (ctx.guild.id,member_per_page,member_per_page*(current -1),))
            index = member_per_page*(current-1)
            wynik = curosor.fetchall()


            for entry in wynik:
                index += 1
                member_id = entry[0]
                exp = entry[1]
                member = ctx.guild.get_member(member_id)
                embed.description += f"{index}) {member.mention} - {exp}\n"
            await msg.edit(embed=embed)

        try:
            reaction, user = await self.client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.emoji in emojis, timeout=60.0)

        except asyncio.TimeoutError:
            return await msg.clear_reactions()

        else:
            if reaction.emoji == "➡️":
                current += 1

            elif reaction.emoji == "⬅️":
                current -= 1
            await msg.edit(embed=embed)``` How to do if next page is cleare (or on -) it will return and dont edit page??
upbeat otter
#

How do i use asyncio to sleep for 3 days😅

slate swan
#
await asyncio.sleep(3 * 24 * 60 * 60)
dapper cobalt
upbeat otter
slate swan
dapper cobalt
upbeat otter
upbeat otter
dapper cobalt
#

And btw that's for the bottom one not the top.

upbeat otter
#

there is nothing as -=

brisk helm
slate swan
#

what did u try do to ?

#

whats -=

#

think python 4.0 is out ?? , its a joke lmao

upbeat otter
#

Is there anyway i can check the day of India using datetime module???

fickle turret
#

nvm ._.

slate swan
#

probably like +=

#

lmao

slate swan
brisk helm
brisk helm
fickle turret
slate swan
dapper cobalt
slate swan
slate swan
#

he is tho

brisk helm
slate swan
#

check this

slate swan
#

he is using it tho

#

where ?

#

self.client.wait_for

#

he himself said hes not using it pepe_shrug

brisk helm
dapper cobalt
slate swan
slate swan
#

now here comes the big code

#
@bot.command()
async def cant(ctx):
    timeout = 4
    if ctx.message.author.id == 801474997238366209:
        await ctx.send('type anything')
        def check(m: discord.Message):  # m = discord.Message.
            return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id 
        msg =  await bot.wait_for(event = 'message', check = check, timeout=timeout)
        lst = []
        string = ''
        try:
            try:
                lst.append(msg.content)
                for i in lst:
                    string+=i
                    float(string)
                await ctx.send('its a float / int')
            except (ValueError , TypeError):
                await ctx.send('not a int nor a float')
        except asyncio.TimeoutError:
            await ctx.send(f"**{ctx.author.mention}**, you didn't send any message that meets the check in this channel for {timeout} seconds..")
            return
        embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
        await ctx.send(embed=embed)
``````discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TimeoutError:```
#

why doesnt it not work think

#

timeouterror:

#

what's after that

#

the timouterror wasnt catched altho i had it

#

@slate swan thats the error , notice in my msg = await bot.waitfor(etc)

brisk helm
slate swan
#

i had a timeout

#
import asyncio
import discord
from typing import Union


@bot.command(name="reactiontest")
async def reaction_test(ctx): # waiting for reactions (✅, ❌) here
    await ctx.send(f"**{ctx.author}**, please react with :white_check_mark: or :x: on this message in 60 seconds")
    
    def check(r: discord.Reaction, u: Union[discord.Member, discord.User]):  # r = discord.Reaction, u = discord.Member or discord.User.
        return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id and \
               str(r.emoji) in ["\U00002705", "\U0000274c"]
        # checking author, channel and only having the check become True when detecting a ✅ or ❌
        # else, it will timeout.

    try:
        #                                   event = on_reaction_add without on_
        reaction, user = await bot.wait_for(event = 'reaction_add', check = check, timeout = 60.0)
        # reaction = discord.Reaction, user = discord.Member or discord.User.
    except asyncio.TimeoutError:
        # at this point, the check didn't become True.
        await ctx.send(f"**{ctx.author}**, you didnt react with a ✅ or ❌ in 60 seconds.")
        return
    else:
        # at this point, the check has become True and the wait_for has done its work, now we can do ours.
        # here we are sending some text based on the reaction we detected.
        
        #                         unicode for ✅ :
        #                         https://emojipedia.org/emoji/✅/#:~:text=Codepoints
        if str(reaction.emoji) == "\U00002705":
            return await ctx.send(f"{ctx.author} reacted with a ✅")
            # or we could also add a role here, like so
            # role = await ctx.guild.get_role(ROLE_ID)
            # await ctx.author.add_roles(role)
            
        #                         unicode for ❌ :
        #                         https://emojipedia.org/emoji/❌/#:~:text=Codepoints
        if str(reaction.emoji) == "\U0000274c":
            return await ctx.send(f"{ctx.author} reacted with a ❌")```
#

look at this

#

maybe I'm dumb, but

brisk helm
slate swan
#

you have asyncio.TimeoutError

#

not just TimeoutError

slate swan
upbeat otter
#

i have another problem

slate swan
#

but the full error would be nice

#

oh

#

that's it

#

still same error

upbeat otter
#

How do i use a loop to keep checking the date after one hour and if the date is divisible by 3, it should send a message to the server(i know about which channel and stuff)

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
slate swan
upbeat otter
brisk helm
slate swan
#

why are you passing in event as a kwarg tho

maiden fable
upbeat otter
#

i am not using cogs

maiden fable
#

then remove the self

hasty iron
upbeat otter
maiden fable
#

calm down

upbeat otter
#

ok sir

maiden fable
#

check_date.start()

#

simple. read the docs, they have everything

upbeat otter
#

okkkk, thankkuuuuu

#

thnku

gloomy coral
hoary gust
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User").

`x == y` Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.

`x != y` Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") instances too.

`hash(x)` Returns the member’s hash.

`str(x)` Returns the member’s name with the discriminator.
upbeat otter
#

I have some more things.......

#

How do I check if the today's date is divisible by 3?

#

I have the function to get the current date, but can i check if it is divisible by 3?

visual island
past ermine
#

How to make a global / command. Like MEE6 or Groovy :( rip

slate swan
#

How to get a list of all category channels?

hoary gust
#

Guys which kwarg is used to count the members in the guild

slate swan
#

Hey so i created a ticket system and i don't know how to set channel permission that not everyone will see the channel, just the message author and the staff

maiden fable
#

!d discord.Guild.member_count

unkempt canyonBOT
#

member_count```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
hoary gust
#

Thanks

maiden fable
#

Or

#

!d discord.Guild.members in case u want the list

unkempt canyonBOT
hoary gust
#

It will count the bots too right?

maiden fable
unkempt canyonBOT
#

await create_text_channel(name, *, overwrites=None, category=None, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/stable/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
maiden fable
hoary gust
#

!d discord.Guild.member_count

unkempt canyonBOT
#

member_count```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
hoary gust
#

Will it count the bots too, cause I don't think that this method will @maiden fable

maiden fable
#

It will bro

hoary gust
#

Wdym?

hoary gust
maiden fable
#

It will count

hoary gust
#

Ooh I see

compact field
#

hi guys how can i add button in bot activity with link ?

hoary gust
#

I will fix that

#

No worries

maiden fable
#

Discord Problem

hoary gust
#

Lol

compact field
maiden fable
#

Mhm

#

Discord Limitation

upbeat otter
#

Guys, how do i write the names of people in a txt file, whenever they message

#

only the names

lament mesa
#

you can use the built-in open function

#

!d open

unkempt canyonBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3.10/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3.10/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3.10/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3.10/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
stray stump
#

!d print

unkempt canyonBOT
#

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)```
Print *objects* to the text stream *file*, separated by *sep* and followed by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like [`str()`](https://docs.python.org/3.10/library/stdtypes.html#str "str") does and written to the stream, separated by *sep* and followed by *end*. Both *sep* and *end* must be strings; they can also be `None`, which means to use the default values. If no *objects* are given, [`print()`](https://docs.python.org/3.10/library/functions.html#print "print") will just write *end*.

The *file* argument must be an object with a `write(string)` method; if it is not present or `None`, [`sys.stdout`](https://docs.python.org/3.10/library/sys.html#sys.stdout "sys.stdout") will be used. Since printed arguments are converted to text strings, [`print()`](https://docs.python.org/3.10/library/functions.html#print "print") cannot be used with binary mode file objects. For these, use `file.write(...)` instead.
upbeat otter
#

Is there any way

lament mesa
upbeat otter
#

add the number of messages everytime they message?

#

Like:

#

Black goku = 0 messages

#

again i message

#

it says 1

#

then 2, 3,4 and so on

#
counter = 0
  with open("leaderboard.txt", "r+") as file1:
      for lines in y:
        if lines.strip("\n") == str(message.author.display_name):
          counter += 1
      file1.writelines(f"{str(message.author.id)}\n")
lament mesa
upbeat otter
#

yess

#

i dont want to use a database, due to connectivity problem

lament mesa
#

Then you will need to use a dictionary

upbeat otter
#

ohh

#

i see

crystal harbor
#

what to do

slate swan
#
@bot.command()
async def cant(ctx):
    timeout = 4
    if ctx.message.author.id == 730644317894344734:
        await ctx.send('type anything')
        def check(m: discord.Message):  # m = discord.Message.
            return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id 
        lst = []
        string = ''
        msg =  await bot.wait_for(event = 'message', check = check, timeout=timeout)
        try:
            try:
                lst.append(msg.content)
                for i in lst:
                    string+=i
                    float(string)
                await ctx.send('its a float / int')
                embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
                return await ctx.send(embed=embed)
            except (ValueError , TypeError):
                await ctx.send('not a int nor a float')
                embed = discord.Embed(title=f"requested by {ctx.author}",description=f"\n{msg.content}\n")
                return await ctx.send(embed=embed)
        except (TimeoutError,asyncio.TimeoutError,discord.ext.commands.errors.CommandInvokeError):
            await ctx.send(f"**{ctx.author.mention}**, you didn't send any message that meets the check in this channel for {timeout} seconds..")
            return```
```py
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TimeoutError:```
#

explain why

slate swan
slate swan
#

Someone knows why is this doesn't works?

#

bruh

#

i didnt mean it in a bad way

upbeat otter
slate swan
#

its like this

#

embed.set_image(url=X)

#

wait lemme see

#

the embed works but it don't delete the channel when i click the reaction

upbeat otter
slate swan
upbeat otter
#

lmao

crystal harbor
slate swan
slate swan
slate swan
lament mesa
#

!d collections.defaultdict

unkempt canyonBOT
#

class collections.defaultdict(default_factory=None, /[, ...])```
Return a new dictionary-like object. [`defaultdict`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict "collections.defaultdict") is a subclass of the built-in [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") class and is not documented here.

The first argument provides the initial value for the [`default_factory`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict.default_factory "collections.defaultdict.default_factory") attribute; it defaults to `None`. All remaining arguments are treated the same as if they were passed to the [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") constructor, including keyword arguments.

[`defaultdict`](https://docs.python.org/3.10/library/collections.html#collections.defaultdict "collections.defaultdict") objects support the following method in addition to the standard [`dict`](https://docs.python.org/3.10/library/stdtypes.html#dict "dict") operations:
upbeat otter
#

thanku tho

#

very much thanku

lament mesa
#

😄

vale narwhal
#

How to see how many servers that my bot are in (i wanna set it on bot status) also how to see the server list

slate swan
crystal harbor
#

@slate swan

slate swan
vale narwhal
#

Is there anyway?

#

Like import server list to txt file or in console

slate swan
slate swan
#

also its this

if message.content.startswith('^botservers'):

    await message.channel.send("I'm in " + str(len(client.guilds)) + " servers!")``` my bad
vale narwhal
#

Ah

#

Alr ty

#

I'll try it on my base code

slate swan
#

thumbsup lmk if there is any errors

#

ur using client or bot ?

vale narwhal
#

bot

slate swan
#

oh

floral crypt
#

Hello i need help

#

how do i create a private channel with the bot?

vale narwhal
#

Just realized that it's bot command lol

slate swan
# vale narwhal bot
@bot.event
async def on_ready():
    print('logged in')
    await bot.change_presence(activity=discord.Activity(
        type=discord.ActivityType.playing, name=f"playing {str(len(bot.guilds))} servers"))``` i assume this would work
vale narwhal
#

I want the bot event one

floral crypt
#

and just can enter admins, one role and a person that have reacted to a message

vale narwhal
#

oh yes

slate swan
vale narwhal
#
@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Streaming(name='Minecraft' , url="http://www.twitch.tv/accountname"))
``` my current one
slate swan
vale narwhal
#

But i couldn't find it

slate swan
#

they are a bit confusing pepe_shrug

vale narwhal
#

Idk where it is

slate swan
#

eh

#

you should use the one i showed u

vale narwhal
#

Trying

floral crypt
#

but what is the name

#

the function i mean

#

to create a channel

slate swan
floral crypt
#

channel_create

#

oka

slate swan
#

lemme see 1 sec

vale narwhal
#

Working fine ty!

slate swan
#

i think py await create_guild(name, region=None, icon=None, *, code=None)

slate swan
slate swan
#

text channel right ?

#

yeah its that

#

channel = await guild.create_text_channel('pass the name here')

#

to change perms u could use this

#
overwrites = {
    guild.default_role: discord.PermissionOverwrite(read_messages=False),
    guild.me: discord.PermissionOverwrite(read_messages=True)
}

channel = await guild.create_text_channel('secret', overwrites=overwrites)```
#

its a dict

floral crypt
#

YEP

#

Just saw

slate swan
#

welcome ?

floral crypt
#

thanks

slate swan
#

np

floral crypt
slate swan
#

me when i see ur code errors

#

and mine ofc

lament mesa
boreal ravine
#

NVM.

slate swan
#

Hey people,
Can anyone willingly teach me discord.py? I am really keen to learn, and hopefully I'll be a very good student. I can invest all my time, i just need a live teacher to help and teach me.

vestal owl
#

is it possible for my bot to manage the channel permissions of the channel it creates?

#

Im trying to make it so that anyone can upload attachments

vestal owl
#

bruh

devout sage
#

Hey is there any discord bot developer who would like to be involved in a custom bot project for a partnered server

slate swan
#

Way better

vestal owl
#

from here at least

slate swan
#

K i just asked for some help

#

Idc, if I get one from here or not

#

There are many different places to search

vestal owl
#

oh okay

#

good luck