#discord-bots

1 messages Β· Page 442 of 1

slate swan
#

i'm really confused smh

#

am i in a cog?

#

then you gotta import it

#

cuz im not?

#

No need

#

If you do that you must define it

slate swan
#

from discord.ext import has_permissions

vale pendant
#

If you're not in a cog file, why did you put self?

slate swan
#

let's just fix the problem that we have now and then move on

#

remove the self argument

#

and it should work

slate swan
#

oh alright

#

lemme fix ur code 9ACOSP_pray

#

thanks

final iron
#

I need some help on my mute command. Im getting an unknown role error when I have the role only guess to why its happening is im not searching for the roles correctly. Here is my code

    @commands.command()
    @commands.has_permissions(manage_roles=True)
    async def mute(self, ctx, member: discord.Member=None, *, reason=None):
        member = member or ctx.message.author
        muted_role = discord.utils.get(ctx.guild.roles, name="muted")
        await member.add_roles(member, muted_role)
        if reason == True:
            embed=discord.Embed(description=f"{member} was muted for {reason}.",
                                color=0xff0000,
                                timestamp=ctx.message.created_at)
            embed.set_author(name=f'{member}', icon_url=f'{member.avatar_url}')
            embed.set_footer(text=f"Epic Bot | Discord bot", icon_url='https://cdn.discordapp.com/embed/avatars/1.png')
            await ctx.send(embed=embed)
        if reason != True:
            embed=discord.Embed(description=f"{member} was muted.",
                                color=0xff0000,
                                timestamp=ctx.message.created_at)
            embed.set_author(name=f'{member}', icon_url=f'{member.avatar_url}')
            embed.set_footer(text=f"Epic Bot | Discord bot", icon_url='https://cdn.discordapp.com/embed/avatars/1.png')
            await ctx.send(embed=embed)
slate swan
#

did you type the role name correctly?

final iron
#

yes

#

I made sure of that

slate swan
#

it's case sensitive

final iron
#

ik

slate swan
#

okay

#
@bot.command()
@commands.has_permissions(administrator=True)
async def ban(ctx, member:discord.Member, *, reason=None):
    guild = ctx.guild
    author = ctx.message.author
    if reason == None:
        embed1=discord.Embed(color=discord.Colour.red(), title="Reason Required!", description="You must enter a reason to ban this member.")
        message3 = ctx.send(embed=embed1)
        sleeper=5
        await asyncio.sleep(sleeper)
        await message3.delete()
        return
    else:
        guild = ctx.guild
        await member.ban()
        embed2=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title="Member Banned", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
        embed3=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title=f"You've been banned from **{guild}**!", description=f"Target: {member.mention}\nModerator: **{author.mention}** \n Reason: **{reason}**")
        message4 = await ctx.send(embed=embed2)
        message5 = await ctx.send("βœ” User has been notified.")
        sleeper=5
@ban.error()
async def ban_error(ctx,error):
    if isinstance(error, MissingPermissions):
        await ctx.send('you dont have perms to use this command')
    else:
        ctx.send('there was a error')``` @slate swan
#

oh

#

you put member in the args

#

remove that

#

didn't work

#

you called the member's method, so there's no need to define him inside the function

final iron
#

Theres an issue with that

slate swan
#
Traceback (most recent call last):
  File "C:\Users\\Desktop\TMG Bot\TMG_Bot.py", line 487, in <module>
    @ban.error()
TypeError: error() missing 1 required positional argument: 'coro'
PS C:\Users\\Desktop\TMG Bot>```
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.
final iron
#

I use member: discord.Member to make the embed look nice

slate swan
#

no member arg

#

not in the command's args

slate swan
final iron
#

oh

slate swan
#

I was kinda inunderstandable again....

final iron
#

Alr and do you happen to know the function to dm a user?

slate swan
#

member.send

#

await member.send()

slate swan
#

yeah, that's what it does...

#

Hi

#

hello

final iron
#

So basically I have a tempban command. It works perfectly fine but I would just like to make the default time permanent. So lets say somebody bans someone without a time it would just default to permanent.

#

Could I get some help starting out on that

slate swan
#

this is prolly stupid question how do i make it where the bot can only message in 1 channel?

manic wing
fervent surge
#

um. what?python @bot.event asyc def on_ready(): print('Signed in as', bot.user.name)

#
main.py", line 35
    asyc def on_ready():
    ^
SyntaxError: invalid syntax```
final iron
#

You missed an n

manic wing
gritty flame
#

why does this not work

fervent surge
manic wing
#

i dont know how you did your tempban so it really depends

final iron
#

I can send the code

final iron
manic wing
#

to be honest im too tired and i've been helping people all day, so you can send it but i wont help with a long thing

final iron
#

Its not long

manic wing
#

send it then

final iron
#
    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member : commands.MemberConverter, duration: DurationConverter, *, reason=None):

        multiplier = {'h': 60**2, 'hour': 60**2, 'hours': 60**2, 'd': 60*1*60*1*24, 'day': 60*1*60*1*24, 'days': 60*1*60*1*24, 'w': 60*1*60*1*24*1*7, 'week': 60*1*60*1*24*1*7, 'weeks': 60*1*60*1*24*1*7}
        amount, unit = duration

        await ctx.guild.ban(member, reason=reason)
        if reason == None:
            await ctx.send(f"Banned {member.mention}  for {amount}{unit}")
            await asyncio.sleep(amount * multiplier[unit])
            await ctx.guild.unban(member)
        if reason != None:
            await ctx.send(f"Banned {member.mention} {amount}{unit}. Reason: {reason}")
            await asyncio.sleep(amount * multiplier[unit])
            await ctx.guild.unban(member)
fervent surge
# final iron async def on_ready():

ok, then why doesn't this work:python @bot.event async def on_ready(): print('Bot is ready as: {}'.format(bot.user.name)) await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="your stupid requests"))

#

?

#

same error btw

final iron
#

I also have this

class DurationConverter(commands.Converter):
    async def convert(self, ctx, argument):
        amount = argument[:-1]
        unit = argument[-1]

        if amount.isdigit() and unit in ['h', 'hour', 'hours' 'd', 'day', 'days', 'w', 'week', 'weeks', 'm', 'month', 'months', 'y', 'year', 'years']:
            return amount, unit
final iron
#

I've been meaning to ask whats the point of using .format instead of just using an f string?

fervent surge
manic wing
slate swan
#

wait

#

I'm stupid

manic wing
fervent surge
fervent surge
slate swan
#

you could use a word, for example:
!ban member permanent
and you check if duration equals "permanent"

#

I have no idea how converters work

gritty flame
#

why wont this work, no error.

spring flax
manic wing
#

or just if not member.banner :p

spring flax
#

yeah, why put if None at the end lol

#

just put if member.banner weirdChamp

slate swan
#
if amount == "permanent":
    return amount
```in your converter
then just check it in the command
#

I'm a really slow typer

gritty flame
#

i tried that too bruh

#

if member.banner

spring flax
#

error handler? on_command_error?

gritty flame
#

what

spring flax
#

do you have any of those?

gritty flame
#

yeh

#

what about them

manic wing
#

just do if not not not member.banner is not None

#

its not that hard ^

spring flax
#

you put else: raise(error) right?

gritty flame
#

ofc

#

but what does that

spring flax
#

also, what exactly doesn't work?

gritty flame
#

have anything to do

spring flax
gritty flame
#

it isnt setting

spring flax
#

full code ?

gritty flame
gritty flame
#

ok

#

lmao

#

too much lines

#

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

gritty flame
slate swan
#
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        print("text")``` Can someone explain what this does?
maiden hazel
gritty flame
#

goes through all files in cogs file then checks if filename ends with .py just checks if it is a python file then prints text @slate swan

slate swan
#

is it needed?

#

can i remove it

gritty flame
#

yeh u can

slate swan
#

without any repercussions

gritty flame
#

r u copying peoples code

slate swan
#

cuz i dont need it to print

gritty flame
#

ok remove it

slate swan
gritty flame
slate swan
#

then i guess today im not copying code

gritty flame
#

u are

#

how dont yk what you r coding

slate swan
#

ik

hasty iron
cloud dawn
hasty iron
#

you can make a check for those kind of files

#

check if the filename starts with a _

#

its not bad code

cloud dawn
hasty iron
#

also in most cases people dont have an init file

final iron
#

Is it possible to change font size in an embed?

cloud dawn
#

Different opinions, imo this is just bad practice.

pure reef
#

bro i cant use my bots cmds any idea why ?

cloud dawn
pure reef
#

yes im not that dumb

vale pendant
#

Do you have a on_message event?

pure reef
#

nope

vale pendant
#

Hmmm?

maiden hazel
vale pendant
#

Maybe wrong prefix?

pure reef
#

no errors and prefix is right

slate swan
#

Are the commands in a cog, and if yes, you sure they're properly loaded?

pure reef
#

nah not in a cog

slate swan
maiden hazel
#

do they have the decorator?

pure reef
#

lemme update my vscode rq see if it works

slate swan
#

Will you share the code?

#

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

vale pendant
pure reef
#

one sec

agile goblet
proven elm
#

Yoo guys how would I go about using a .ban to work for MEMBER + USER so .ban @proven elm and .ban 840918164316618772

pure reef
#

its on jsut wont do anything

final iron
#

Whats the function to display a users name without their discriminator?

final iron
#

oh im stupid

proven elm
agile goblet
#

allows you to typehint 2 or more things

#

instead of just 1 thing

#

!d typing.Union

unkempt canyonBOT
#

typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.

To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
opaque trail
#

!d typing.Union

unkempt canyonBOT
#

typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.

To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
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.
agile goblet
#

what no

#

he wants both member and user

proven elm
#

yea

#

if I seperate it into TWO commands aka .ban and .bann for user and member it works

dapper cobalt
proven elm
#

but I want .ban for both

dapper cobalt
cloud dawn
#

user object does not have .ban

opaque trail
#

ban a user?

proven elm
#

tons of bots can?

#

I swear

maiden hazel
#

?

pure reef
#

ban by ids

hasty iron
#

typehint to User only

proven elm
#

ye

cloud dawn
#

Yeah they can because they ban him globally

pure reef
#

ik how to do it but im not gonna tell cuz they can be used for bad thingfs

hasty iron
#

globally?

pure reef
#

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

proven elm
hasty iron
final iron
stiff nexus
#

how do i get my bots uptime in the new timestamp formate??

proven elm
#

You can ban via ID I have done it but with two different commands

pure reef
#

if you scrape member ids you can ban way faster than just making the bot look for all the members

proven elm
#

.ban and .bann cause I cant reuse same name for two commands

agile goblet
#

guild.ban(user)

#

u can ban users lmao

#

why wouldnt you be able to

pure reef
agile goblet
#

thats besides the point tho

opaque trail
#

user does not have a ban method because it isnt in a guild

opaque trail
#

but you can add a user to the ban records

proven elm
#

I have done it but not with the same .ban

oblique cobalt
maiden hazel
opaque trail
pure reef
#

idc 😭 its in 1 server

agile goblet
agile goblet
#

!d typing.Union

unkempt canyonBOT
#

typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.

To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
opaque trail
agile goblet
#

def func(var: str)

pure reef
#

they can nuke the server with jsut me and the bot

agile goblet
#

var: str
thats typehinting

pure reef
#

couldnt care less

opaque trail
#

lmfap

#

loneliness

agile goblet
#

basically converting the argument into a string

proven elm
agile goblet
#

yea

proven elm
#

so where do I put the typing.Union

agile goblet
#

instead of discord.User do typing.Union[x, y]

pure reef
#

but nothing abt the code?

agile goblet
#

import typing

#

dont forget

agile goblet
opaque trail
#

why would you use union tho? why dont you just typehint to user and whatever happens, the same user gets banned

proven elm
#

getting errors

hasty iron
#

context objects have no attribute user

#

and thats not how you typehint

#

nubz showed you before what a typehint is

opaque trail
proven elm
#

oh should I put the typehint inside the []

opaque trail
#

and incase you do typehint (i dont understand why), youll have to check the instances

oblique cobalt
agile goblet
#

it takes an abc.Snowflake

hasty iron
#

guild.ban takes any object with an id attribute

opaque trail
#

exactly, but you guys are typehinting to a member or a user, why dont you just typehint to a discord.User and ctx.guild.ban(user)?

proven elm
opaque trail
#

you dont need to use union?

oblique cobalt
opaque trail
#

well yea, i guess you can because user is an api call

oblique cobalt
#

yeah

hasty iron
#

if the user is not in cache then its an api call

opaque trail
proven elm
#

I am still unsure how to ban someone by their ID

hasty iron
#

use discord.Object

oblique cobalt
#

guild.ban(discord.Object(id here))

cloud dawn
proven elm
#

Yeah but that means I can only ban via @proven elm

#

not ban via 493537125564940309

#

an ID

cloud dawn
hasty iron
#

the member converter accepts mention, name and id

oblique cobalt
hasty iron
#

!d discord.ext.commands.MemberConverter

unkempt canyonBOT
#

class discord.ext.commands.MemberConverter```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
waxen tangle
#

how can i read my bots dms n stuff?

proven elm
#

when I do .ban 493537125564940309 it says Member "493537125564940309" not found

oblique cobalt
#

!d discord.User.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
opaque trail
#
async def ban(ctx, user: typing.Union[discord.Member, discord.User], reason: str = None):
   await ctx.guild.ban(user)
``` try this
proven elm
#

ty

opaque trail
#

and just add your reasons and shit

pure reef
#

how do i change my discord.py version again ? forgot

pliant gulch
#

Why do you need to typehint member as well?

#

Your banning them so I doubt you would need their guild data

opaque trail
pliant gulch
#

Yes, user grabs from cache as well

opaque trail
#

depends

#

oh wait

#

that doesnt make any sense

pliant gulch
#

You know converting to discord.Member can do an API call as well right???

pliant gulch
#

Still possible

opaque trail
# proven elm ty

instead you can just typehint to a discord.User you dont need a union really
because you will still get it from the cache

oblique cobalt
pliant gulch
proven elm
#

also how do I do ctx.send to a specfic channel

pliant gulch
#

Ofc if you don't have intents it wouldn't work either way I dont think

hasty iron
#

iirc not all members get sent with the GUILD_JOIN payload if it’s a big guild

opaque trail
cloud dawn
proven elm
#

Get the id of the channel?

oblique cobalt
unkempt canyonBOT
opaque trail
unkempt canyonBOT
opaque trail
#

or fetch channel

proven elm
#

883085625727778846 id of the channel is something like this init?

opaque trail
#

get gets the channel from cache fetch calls api

opaque trail
proven elm
#

so where do I put channel.send() to send to a specific channel along with my message?

oblique cobalt
opaque trail
#
channel = bot.get_channel(...)
await channe.send(...)
proven elm
#

works great thank you

manic wing
#

@pliant gulch whats the different between bot.get_channel and guild.get_channel?

proven elm
#

you know the first thing you do

manic wing
#

…

proven elm
#

1 sec ```py
client = commands.Bot(command_prefix = '.', intents=intents, help_command=None)

#

This^

manic wing
#

!d discord.Guild.get_channel

unkempt canyonBOT
manic wing
proven elm
#

oh sorry

manic wing
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
manic wing
#

2 different ways

#

im asking andy what the difference is

pure reef
#
embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
``` how do i put color = into that
jagged root
#

how can i purge 1 message

#

on an event

#

for example bot triggers word hello and it gets deleted

#

not author message just purge 1 message

proven elm
#

how do I detect if someone is banned so I can use if statements on it

#

like if user_banned == false:
ctx.send("User is not banned")

#

something like that

manic wing
jagged root
#

no

#

purge 2 message

#

but alr got it thankls

pure reef
#
cursor.execute(f"SELECT msg FROM main WHERE guild_id = {ctx.guild.id}")
         result1 = cursor.fetchone()
         members = len(list(ctx.guild.members))
         mention = ctx.author.mention
         user = ctx.author.name
         guild = ctx.guild
         embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
         
         channel = bot.get_channel(int(result[0]))
         await channel.send(embed=embed)``` any ideas why this would return none ?
manic wing
#

what returns none?

pure reef
#

the embed description

#

it just says None

#
@bot.command()
async def testwelc(ctx, member=None):
    db = sqlite3.connect('main.sqlite')
    cursor = db.cursor()
    cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
    result = cursor.fetchone()
    if result is None:
         return
    else:
         cursor.execute(f"SELECT msg FROM main WHERE guild_id = {ctx.guild.id}")
         result1 = cursor.fetchone()
         members = len(list(ctx.guild.members))
         mention = ctx.author.mention
         user = ctx.author.name
         guild = ctx.guild
         embed = discord.Embed(description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
         
         channel = bot.get_channel(int(result[0]))
         await channel.send(embed=embed)
``` full code
slate swan
#
@commands.command()
    async def baltop(self, ctx):
        self.addnet()
        cursor = collection.find().sort('net', pymongo.DESCENDING)
        docs = await cursor.to_list(length = 10)
        for doc in docs:
            print(doc['name'] + " " + str(doc['net']))

        print(docs)```
Why is this giving this?

Traceback (most recent call last):
File "/home/turtle/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/turtle/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/turtle/.local/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: KeyError: 'net'```

slate swan
# slate swan ```py @commands.command() async def baltop(self, ctx): self.addnet()...

btw, this is addnet

    @commands.command()
    async def addnet(self, ctx):
        for member  in ctx.guild.members:
            await self.open_bank(member)
            await asyncio.sleep(.1)
            mem = await collection.find_one({'_id': member.id})
            net = mem['wallet'] + mem['bank']
            await collection.update_one({'_id': member.id}, {'$set': {'net': net} }, upsert = True)
            print(str(mem['_id']) + " " + str(mem['net']) )```
full lily
slate swan
full lily
#

gotcha

pure reef
#

ugh

#
@bot.event
async def on_member_join(member):
     db = sqlite3.connect('main.sqlite')
     cursor = db.cursor()
     cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
     result = cursor.fetchone()
     if result is None:
         return
     else:
         cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
         result1 = cursor.fetchone()
         members = len(list(member.guild.members))
         mention = member.mention
         user = member.name
         guild = member.guild
         embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
         
         channel = bot.get_channel(int(result[0]))
         await channel.send(embed=embed)
 error:  KeyError: 'member'```
#

error at the botto,

#

it literally wont work

hasty iron
#

the string for the description doesn’t contain {member}

pure reef
#

it needs to?

hasty iron
#

i believe so

pure reef
#

thats whats in my db, thats what the description is supposed to be, mention = member.mention

full lily
#

is mention an attribute or method?

hasty iron
#

oh wait actually

#

the key error is for member not members

pure reef
#

in my code i have py mention = member.mention

hasty iron
#

can you send the full traceback

pure reef
#
 File "c:\Users\dctho\OneDrive\Desktop\Theft (NEW)\main.py", line 57, in on_member_join
    embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
KeyError: 'member'
``` thats the full thing
hasty iron
#

did you save your code

pure reef
#

lemme try now

#

still says same thing

trim fulcrum
#
PS C:\Users\kamma\OneDrive\Desktop\New Bot> python main.py
We are in production
Traceback (most recent call last):
  File "main.py", line 18, in <module>
    bot.run(DISCORD_BOT_TOKEN)
  File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Users\kamma\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'bool' object has no attribute 'strip'```

what does that mean
crisp pine
#

How do i make it dm the person that they got kicked from the server?

pure reef
#
await member.send('you got kicked')
crisp pine
#

can it fit in here?

    @commands.has_permissions(kick_members=True)
    @commands.command()
    async def kick(self, ctx,  user: discord.Member, *, reason="No reason provided"):   
        if ctx.author.top_role > user.top_role or ctx.author == ctx.guild.owner:
            if user == ctx.author:
                return await ctx.send("***:no_entry: You can't softban yourself...***")
           
            kick = discord.Embed(color=0x2f3136, title=f":heartbroke_certimoderator: {user} was Kicked", description=f"**```_{user} was kicked\n by {ctx.author}_```**")
            kick.set_footer(text = f"{ctx.author} kicked {user}")
            kick.set_thumbnail(url = user.avatar_url)
            await ctx.channel.send(embed=kick)
            await user.send(embed=kick)
            await user.kick(reason=reason)```
#

i tried yesterday and it did not work

pure reef
#

shit wont workkkkkk

crisp pine
#

and alose i putted

            await member.send('you got kicked')
            await user.send(embed=send)```
#

could that word?

pure reef
#

no do await user.send

crisp pine
#

the what

#

i have a kick code already

pure reef
#

await user.send('you got kicked')
await user.send(embed=send)

crisp pine
#

i just need it to dm the person that they kicked

pure reef
#

embed = send ?/

crisp pine
#

lemme show

vale pendant
#

?

#

Where do you get send and message from?

pure reef
#

im conjfused now

crisp pine
#
    message = f"You have been kicked from {ctx.guild.name} for {reason}"
    await member.send(message)```
#

can that work?

pure reef
#

mhm u can do that

vale pendant
#

yes because message is defined.

pure reef
#

make member user tho cuz thats what your using

crisp pine
#

but where i put

    message = f"You have been kicked from {ctx.guild.name} for {reason}"
``` in my code?
pure reef
#

File "c:\Users\OneDrive\Desktop\Theft (NEW)\main.py", line 57, in on_member_join
embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
KeyError: 'member'

#

scripts can u help ?

crisp pine
#

ok

#

ima test

slate swan
#
@bot.command(name="urban")
async def urban(ctx, *, msg):
    word = ' '.join(msg)
    api = "http://api.urbandictionary.com/v0/define"
    # Send request to the Urban Dictionary API and grab info
    response = requests.get(api, params=[("term", word)]).json()
    embed = discord.Embed(description="No results found!", colour=0xf6dbd8)
    if len(response["list"]) == 0:
        return await ctx.send(embed=embed)
    # Add results to the embed
    embed = discord.Embed(title="Word", description=word, colour=embed.colour)
    embed.add_field(name="Top definition:", value=response['list'][0]['definition'])
    embed.add_field(name="Examples:", value=response['list'][0]['example'])
    embed.add_field(name=f"Written On:", value=response['list'][0]['written_on'])
    embed.add_field(name=f"Upvotes:", value=response['list'][0]['thumbs_up'])
    embed.add_field(name=f"Downvotes:", value=response['list'][0]['thumbs_down'])
    await ctx.send(embed=embed)

@urban.error
async def urban_error(ctx,error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.reply(f"`Usage` - `^urban [Word]`")``` help, the error message wont send
pure reef
#
@bot.event
async def on_member_join(member):
     db = sqlite3.connect('main.sqlite')
     cursor = db.cursor()
     cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {member.guild.id}")
     result = cursor.fetchone()
     if result is None:
         return
     else:
         cursor.execute(f"SELECT msg FROM main WHERE guild_id = {member.guild.id}")
         result1 = cursor.fetchone()
         members = len(list(member.guild.members))
         mention = member.mention
         user = member.name
         guild = member.guild
         embed = discord.Embed(color=lol,description=str(result1[0]).format(members=members, mention=mention, user=user, guild = guild))
         
         channel = bot.get_channel(int(result[0])
``` full code
``` full code
vale pendant
slate swan
#

oh nvm

#

ok ya te reply part is right

vale pendant
#

Hmmm, the error handler looks correct.

slate swan
pure reef
#

so no ?

vale pendant
#

Maybe it's because of the *, I might be wrong though.

vale pendant
marsh depot
#

How can i obtain all the guilds id my bot are?

vale pendant
#

I don't see member in the embed though.

pure reef
#

would any of this make a difference

vale pendant
vale pendant
crisp pine
#

How i turn this into a embed?

 message = f"_You have been banned from_ **{ctx.guild.name} by {ctx.author}**"```
vale pendant
pure reef
#

fuck

vale pendant
slate swan
#

How can i make my bot ask something, then wait for a message & continue ?
Kind of what Easy Applications is doing

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
kindred epoch
#

read that and add it

slate swan
#

!pip

#

!pep

unkempt canyonBOT
#
Missing required argument

pep_number

full lily
#

you have to send the embed

crisp pine
#

ik

#

it dms the banned user

#

thats not it

full lily
#

show me how you're sending it

crisp pine
#

Nvm I Got It

#

This What Should Be There

            await user.send(embed=embed)

but i placed

            await user.send(embed)```
full lily
#

right

slate swan
#

hey so im trying to make my bot play files in a voice call and the source works fine, but i get this error

ERROR: ffprobe/avprobe and ffmpeg/avconv not found. Please install one.```
#

ive looked into ffmpeg but im not sure how to use it

#

is there a way you can get the default help command to show group commands aswell?

proven elm
#

how do I detect if someone is banned so I can use if statements on it
like if user_banned == false:
ctx.send("User is not banned")
something like that

pallid meadow
#

You would need to keep track of who you ban.

#

So you would need to put it into a database or something.

#

@proven elm ^^^

vale pendant
#

Not really, can't you just check the guild bans and see if the user is in there or not?

proven elm
pallid meadow
#

Let me check real quick

vocal plover
#

await guild.bans()

proven elm
#

whats this

pallid meadow
#

ig you can

#

I've never used that before

proven elm
#

im not sure how to correctly use it

pallid meadow
#

so it returns a list

#

and you would iterate over that list until the user id matches

#

if it doesn't then they aren't banned, but if it matches then they are banned

vocal plover
#

are you making an unban command?

pallid meadow
#

I think it's a command to check if someone is banned or not

proven elm
#

it keeps banning them

#

even if theyre already banned

vocal plover
#

ah

proven elm
#

like it says "user has been banned"
so I wanna see if theyre banned then use an if statement to stop it saying theyre already banned

vocal plover
#

create guild ban will return a 400 response if the user is already banned, so you can wrap it in a try/except

proven elm
#

create guild ban? how would I use that

vocal plover
#

guild.ban()

proven elm
#

ah

vocal plover
#

I'm just kinda used to the api name for it, rather then the discord.py name

proven elm
#

ah gotcha

#

is there an easier way to stop me from being able to .ban user repeatedly

vale pendant
#

You can add a command cooldown.

proven elm
#

yeah but I physically dont want it saying "banned user" if theyre already banned

vale pendant
#

You can do what jacobo said.

pallid meadow
vale pendant
#

Yeah you can.

pallid meadow
#

so it would be something like

try:
  # Code
except discord.HttpException(response, message):
  if response.status == 400:
    # Code
#

@proven elm

dapper cobalt
#
@tasks.loop(hours=12)
    async def check_members_status(self):
        guild = self.bot.get_guild(883004767025111050)
        members = guild.members
        success = []
        channel = self.bot.get_channel(883119910857875476)
        for member in members:
            if member.activity == None:
                continue
            if member.status == discord.Status.offline:
                continue
            if "something" in member.activity:
                data = await get_account(member.id)
                if data == "not found":
                    continue
                else:
                    accounts.update_one({"userId": str(member.id)}, {
                                        "$inc": {"points": 3}})
                    success.append(member.mention)
            else:
                continue

I'm trying to iterate through each member in the guild and checking their custom activity, however, I get TypeError: argument of type 'CustomActivity' is not iterable even tho when I test it in my eval command it works.

#

I had to make it a string using str().

stray fox
#

Would anyone here happen to know how to automate onboarding of patreon customers in discord?

proven elm
#

why am I getting this error

sweet oxide
#

How can I delete the original message I sent containing buttons? The user will click the close/delete button and the message will self destruct. Here is how it would look like:

await ctx.send(embed=embed, components=[action_row])
#Do  irrelevant stuff
button_ctx = await wait_for_component(self.bot, components=action_row,
                                                      timeout=600)
if button_ctx.custom_id == 'next' + msg:
  await button_ctx.edit_origin()#Change embed
elif button_ctx.custom_id == 'close' + msg:
  await button_ctx # I want to delete the original message
  return
marsh depot
#

Why are there times when I do a slash command and it answers this?

There are times that the command works correctly but other times that when I do it I get this message

Traduction :: Invalid interaction application command

visual island
proven elm
#

now I get this

#

AttributeError: 'Guild' object has no attribute 'get_ban'

visual island
#

what's get_ban

hasty iron
#

i think its fetch_ban

proven elm
#

oh ok

proven elm
#

why does my bot not work in another server

#

no commands work

#

actually no

#

the only command that doesnt work is .is_banned 840918164316618772

pallid meadow
#

Just except the 400 error

hasty iron
#

get_user returns None if its not in cache

proven elm
proven elm
#

no users in server?

hasty iron
#

if the bot doesn’t have any shared guilds with that user

#

the bot wont be able to recognize them

pallid meadow
#

Yeah so that's why I wouldn't do that @proven elm because it won't always work

proven elm
#

yeah but it doesnt work for me

#

I mean like it doesnt DM me

proven elm
hasty iron
#

did you put your id?

proven elm
#

yea

pallid meadow
#

Something like that

#

Let me just check if anything else raises a 400

hasty iron
#

and then use exc

pallid meadow
proven elm
#

like

#

.banned ID or ?

pallid meadow
#

you would get the user object

#

so you would have user as a parameter in your command

proven elm
pallid meadow
#

alright copy this new code

try:
  await user.ban()
except discord.HttpException as exc:
  if exc.response.status == 400:
    await ctx.send("This user is already banned")
#

do you understand this code?

calm pawn
#

Would it be possible to run bot commands from a prompt thing that I might have in a program window, oppose having to type the command in the chat?

pallid meadow
#

so user.ban() will raise a 400 error if the user is already banned from the guild

#

and all this does is check if that status code is a 400 error.

proven elm
#

what is a 400 error

#

also how do I tell the bot to check specific users and raise the error

pallid meadow
#

It means bad request

#

So have you ever run into a 404 not found error @proven elm

proven elm
#

yeah

pallid meadow
#

It's the same thing, just a different error.

proven elm
#

so how do I tell the bot to check a specific user and raise the error

pallid meadow
#

so this is for the ban command correct?

#

or is it just to check if the user is banned or not

proven elm
#

to check if the user is banned

#

but I do want to use it so it doesnt let me ban him again

pallid meadow
#

Ohhh I see

proven elm
#

like display the ban message AGAIN if hes banned

pallid meadow
#

so yeah for the ban command my solution would work

#

but to check if someone is banned, that wouldn't work. Because it will ban them if they aren't already banned.

proven elm
#

like cause if I spam .ban ID then it keeps saying "user has been banned"

#

even thought the first time they got banned

pallid meadow
#

Yeah so you would do what I did

#

are you passing in user id's or are you pinging them?

#

when you actually execute the command that is

proven elm
#

@pallid meadow

slate swan
crisp pine
#

Is It Possible to dm a ban user that they got unbanned when you run the unban command?

slate swan
#

If it has a shared server with the bot yes

proven elm
#

@slate swan

slate swan
#

Define what message is

proven elm
visual island
#

have a default value

covert igloo
#

hey i wanted to make a simple command but my output keeps coming back with "Callback for ping command is missing 'ctx" parameter."

#

oh nvm i got it

ivory drum
#
global nsfw

@bot.command()
async def nsfw(ctx, value):
  value = value.lower()
  if value == "on":
    nsfw = True
    await ctx.send("NSFW has been successfully turned on.")
  elif value == "off":
    nsfw = False
    await ctx.send("NSFW has been successfully turned off.")
  else:
    await ctx.send("NSFW is currently " + nsfw)``` when i run :nsfw status it gives me "local variable referenced before assignment" even when i have ran :nsfw off before that, how do i fix this?
clever wind
#

is there a way to get the vc id that the cmd author is in?

valid niche
valid niche
wicked atlas
#

pretty sure that globals in general aren't very nice

ivory drum
# valid niche Could you share the full traceback?

sure: ```Ignoring exception in command nsfw:
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 "main.py", line 62, in nsfw
await ctx.send("NSFW is currently " + nsfw)
UnboundLocalError: local variable 'nsfw' referenced before assignment

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: UnboundLocalError: local variable 'nsfw' referenced before assignment```

valid niche
#

You’re only setting NSFW in the if/elif

#

Which gets cleared after the command ends so it does jack all

#

And in the else the NSFW variable is never assigned

ivory drum
#

oh i see

#

how do i save it? i tried adding global nsfw before the command

agile goblet
#

youre supposed to define it outside the function and global it inside the function

#

thats saved in cache tho so

#

might be better to actually save it in your case

ivory drum
#

oh alright

clever wind
#

lmao

agile goblet
#

in other words, when you close your bot and start it again it will reset the value

valid niche
#

Like make it a new attribute to bot if you really need it

#

But don’t use global

ivory drum
#

oh well i fixed it using ```py
nsfw = True

@bot.command()
async def nsfw(ctx, value):
global nsfw
value = value.lower()
if value == "on":
nsfw = True
await ctx.send("NSFW has been successfully turned on.")
elif value == "off":
nsfw = False
await ctx.send("NSFW has been successfully turned off.")
else:
await ctx.send("NSFW is currently " + str(nsfw))``` but for some reason when i run :nsfw status it gives "nsfw" if i don't set nsfw with :nsfw off

valid niche
#

Please do NOT use global

vocal plover
#

also your command is named nsfw

ivory drum
#

how do i add an attribute to bot?

valid niche
#

And conflicting names yeah

vocal plover
#

which means everything here is a big mess of weird references

ivory drum
#

oh right lmao

vocal plover
#

did the tag for bot vars get merged

#

!bot-vars

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

valid niche
ivory drum
#

thanks

spare agate
#

I created a code to start a java from my python, its related to my bot, but its saying that the system was not able to find the file, even if its there. Also I didn't specified the name, and still was able to find, how can I fix it? The error its in portuguese, but I already translated it here

#

this is my code

valid niche
#

It’s better for naming, it carries over to cogs, it’s less prone to errors

valid niche
spare agate
#

but its my bot

valid niche
spare agate
#

I used lavalink, to play music on my discord bot

valid niche
#

I don’t see anything related to a discord bot in the issue, description, code or anywhere

spare agate
#

ok thks

crisp pine
#

Is It Possible For Spotify Commmand?

#

Why The Command Would Not Reply?

@client.command()
async def spotify(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
        pass
    if user.activities:
        for activity in user.activities:
            if isinstance(activity, Spotify):
                embed = discord.Embed(
                    title = f"{user.name}'s Spotify",
                    description = "Listening to {}".format(activity.title),
                    color = 0xC902FF)
                embed.set_thumbnail(url=activity.album_cover_url)
                embed.add_field(name="Artist", value=activity.artist)
                embed.add_field(name="Album", value=activity.album)
                embed.set_footer(text="Song started at {}".format(activity.created_at.strftime("%H:%M")))
                await ctx.send(embed=embed)```
slate swan
#

hmm

#

well I'm not the one to ask, since I literally started coding yesterday and I only know how to make a discord bot insult you, but maybe you capitalized smth wrong?

#

ik python is very strict on capitalization

rapid pebble
#

how would i be able to send a dm? im tryin to do ctx.author.send(msg) but i get a error saying: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

sweet pilot
#

how can I unregister (remove ) a command

#

commands.Bot.remove_command did the job

wispy spade
dawn vine
#

what does ctx mean?

wispy spade
#

hmm, ctx refers to the context where the command was executed

#

it commonly refers to things like the user and message that triggered the command, the channel and guild it happened in, etc.

dawn vine
#

oh thanks

rapid pebble
#

thanks tho

covert igloo
#

i was following a cogs tutorial and i keep getting "cogs.example has no setup function"

#

am i doing something wrong

supple thorn
#

is there a way to see what you printed like when using a eval command

lament mesa
visual island
#

are there any ways to get the __dict__ attribute of discord.Message or I can only get __slots__?

slate swan
#

at the end of the cog you have to do

def setup(bot)
bot.add_cog(className(bot))

lament mesa
unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

Values printed: test
lament mesa
#

@supple thorn

slate swan
#

!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
#
intents = discord.Intents().all()
bot = commands.bot(command_prefix="!",case_insensitive=True, intents=intents)
bot.remove_command('help')

line 5 in module
line 5 is bot = commands.bot(command_prefix="!" that stuff
module object is not callable

unkempt canyonBOT
#

discord/message.py line 605

__slots__ = (```
lament mesa
#

oh nvm mb

slate swan
#

lol thx i just realized

#

simple mistake hahha

crisp pine
#

Can someone help me with spotify command it give no errors but the command would not reply..

#
@client.command()
async def sp(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
        pass
    if user.activities:
        for activity in user.activities:
            if isinstance(activity, Spotify):
                embed = discord.Embed(
                    title=f"{user.name}'s Spotify",
                    description="Listening to {}".format(activity.title),
                    color=0xC902FF)
                embed.set_thumbnail(url=activity.album_cover_url)
                embed.add_field(name="Artist", value=activity.artist)
                embed.add_field(name="Album", value=activity.album)
                embed.set_footer(text="Song started at {}".format(
                    activity.created_at.strftime("%H:%M")))
                await ctx.send(embed=embed)```
stark hearth
#

how do you make the roles like no cut off

#
    @commands.command(aliases=["whois"])
    async def userinfo(self, ctx, member: discord.Member):

        roles = [role for role in member.roles][1:]

        embed = discord.Embed(
            description = f'**User Infomation - **{member.mention}',
            colour=member.color, 
            timestamp=ctx.message.created_at
            )

        embed.set_thumbnail(url = member.avatar_url)
        embed.set_footer(text=f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)

        embed.add_field(name='ID:', value=f'`{member.id}`')
        embed.add_field(name='Nickname:', value=member.display_name)

        embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
        embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))

        embed.add_field(name=f'Roles ({len(roles)})', value=" ".join([role.mention for role in roles]))
        embed.add_field(name='Top Role:', value=member.top_role.mention)

        embed.add_field(name = 'Bot:', value = member.bot)

        await ctx.send(embed=embed)
final iron
#

I basically replicated dank memers hack command but for some reason this message is sending

<Message id=883174350872805386 channel=<TextChannel id=813823051774165042 name=':pencil:general' position=5 nsfw=False news=False category_id=789941689791283210> type=<MessageType.default: 0> author=<Member id=868156490022789130 name='Epic bot' discriminator='8161' bot=True nick=None guild=<Guild id=788123028302594079 name="test" shard_id=None chunked=True member_count=27>> flags=<MessageFlags value=0>>
lament mesa
final iron
#

The message sends right after the hack message sends

#

Right at the beginning

visual island
lament mesa
lament mesa
visual island
visual island
#

btw

#

what should additional_slots be

lament mesa
visual island
#

ValueError: '__slots__' in __slots__ conflicts with class variable yay

lament mesa
slate swan
#

anyone knows how to host with AWS video or anything related

regal rapids
#

how do i check how long ago a message was sent in a channel and if its over so long ago i send a message

boreal ravine
vagrant brook
#

ctx.member isn't a thing

#

Maybe you mean ctx.author?

stark hearth
boreal ravine
#

uh ```py
@commands.command(aliases=["whois"])
async def userinfo(self, ctx, member: commands.MemberConverter=None):
if member == None:
member = ctx.author

  embed = discord.Embed(title="User Info")
  embed.set_thumbnail(url=ctx.member.avatar_url)
  embed.add_field(name="ID:", value=ctx.author.id)
  embed.add_field(name="Display Name:", value=ctx.member.display_name)
  embed.add_field(name="Account Created At:", value=ctx.member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
  embed.add_field(name="Joined At:", value=ctx.member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
  embed.add_field(name="Roles:", value=f"{len(ctx.member.roles)}")
  embed.timestamp = datetime.utcnow()
  await ctx.send(embed=embed)
stark hearth
#

its a long process but there some yt videos on it

slate swan
#

damn

#

i dont have a card yet

#

πŸ˜”

stark hearth
slate swan
#

dont know any good ones for free aPES_Think

stark hearth
#

but you can use heroku though

slate swan
stark hearth
#

heroku has a free 450 hours

#

then you need to pay

slate swan
#

on each account ?

#

or do they check my hardware ID

gloomy coral
#
    @commands.Cog.listener()
    async def on_ready(self):
      global startTime 
      startTime = time.time()

    #create a command in the cog
    @commands.command(name='Uptime',aliases=['uptime','onlinetime'])
    async def _uptime(self,ctx):

        # what this is doing is creating a variable called 'uptime' and assigning it
        # a string value based off calling a time.time() snapshot now, and subtracting
        # the global from earlier
        
        
        uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
        await ctx.send(f"Chad has been online for {uptime}")```
#

how to add days here?

lament mesa
#

dont use globals

#

!bot-var

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

dense lily
#

does anyone know if I can set a custom status to my bot that is just text

#

without the 'Playing' or 'Listening to' prefix

lament mesa
#

I dont think that bots have that yet

dense lily
#

dang

#

thats annoying

opal pewter
#

Oddly enough, the customactivity thing doesn't work

slate swan
#

hi guys

lament mesa
#

@unkempt canyon Bot has it

dense lily
slate swan
#

discord developer portal

dense lily
#

the dashboard thing?

slate swan
#

Where you make the bot

slate swan
dense lily
#

ok so I can't dynamically change it from the code

slate swan
#

No sir

lament mesa
dense lily
#

ok

#

thanks for the help

slate swan
#

hey does anyone have better code for music systems? Its buggy and/or glitchy as hell every so often. from discord import FFmpegPCMAudio from discord import TextChannel from youtube_dl import YoutubeDL ```@bot.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(bot.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("**Music is playing.**")


else:
    await ctx.send("**Music is already playing.**")
    return```
dense lily
#

lol im actually working on a music system rn

slate swan
#

lol

dense lily
#

its very bad tho

slate swan
#

rip

#

Lol, i gtg

#

bye guys

dense lily
#

bye

vale narwhal
#

How to toggle the bot event? Like using command to enable/disable it

#

My current event code

@bot.event
async def on_member_remove(member):
	await member.ban()
	print(f"Banned {member} ")
dense lily
#

wdym

vale narwhal
maiden hazel
dense lily
#

im kinda new to this

maiden hazel
brisk helm
gloomy coral
lament mesa
clever wind
#

how do u spilt a list of 8 none types randomly into 2 spilts

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
#

pog

reef trail
#
def get_prefix(self, bot, message):
    try:
        cursor.execute(
            f"SELECT prefix FROM guilds WHERE guildId = {message.guild.id}")
    except:
        pass
    for row in cursor.fetchall():
        self.prefixes = row[0]
    prefix = self.prefixes if getattr(
        message, 'guild', None) else self.default_prefix
    mydb.commit()
    return commands.when_mentioned_or(prefix)(bot, message)```
 how can i make this ignore capitalization?
hasty loom
#
msg = await channel.send(
    f"![loading](https://cdn.discordapp.com/emojis/883205345705619468.webp?size=128 "loading") Adding this channel to the database... {ctx.guild.owner.mention}"
)

await msg.edit(
    f"{ctx.guild.owner.mention}, the setup is successful! **Currently, @everyone cannot see this channel.** You may send more messages here, delete my messages, or change the channel name or topic. You can also delete the channel if you don't want to have this feature anymore. You can unlock this channel when you are done."
)

TypeError: edit() takes 1 positional argument but 2 were given does this not take one arg?

slate swan
#

msg.edit(content=)

hasty loom
#

oh

novel eagle
#

hello

proper root
#

How would I use the new discord buttons feature?

lament mesa
exotic patrol
hasty loom
#

whats the event for when a channel is deleted?

lament mesa
#

!d discord.on_guild_update

unkempt canyonBOT
#

discord.on_guild_update(before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") updates, for example:

β€’ Changed name

β€’ Changed AFK channel

β€’ Changed AFK timeout

β€’ etc...
maiden fable
#

!d discord.on_guild_channel_update

unkempt canyonBOT
#

discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
maiden fable
unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

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

oh that exists

#

good to know

slate swan
lament mesa
#

thats the class

slate swan
lament mesa
#

what do you want to write?

slate swan
#

i want the name of user

lament mesa
#

What did you expect vs the result

lament mesa
slate swan
#

ohk

slate swan
lament mesa
#

πŸ‘

slate swan
#

?plis

lament mesa
#

sorry, bit busy rn

waxen granite
#

How can i get a specific msg in a specific channel only?

#

Without id

#

Like the msg contains a specific phrase

slate swan
slate swan
slate swan
lament mesa
slate swan
lament mesa
#

wdym nothing is working?

lament mesa
keen talon
slate swan
#

may i invite u can also check plssss

keen talon
#

k

slate swan
slate swan
lament mesa
#

maybe you have an on_message event?

slate swan
lament mesa
#

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

hasty loom
#
        await ban(
            user=message.author,
            reason=f"Sent a message in {message.channel.mention}",
            delete_message_days=1,
        )

TypeError: ban() got an unexpected keyword argument 'user' πŸ€”

steep estuary
#

how to make a react command :/

hasty loom
steep estuary
keen talon
#

!d discord.Message.add_reaction

hasty loom
#

ah its case sens

lament mesa
lament mesa
hasty loom
#
@bot.listen("on_message")
async def ban(message):
    if await bot.db.fetchval(
        "SELECT EXISTS (SELECT id FROM banchannels WHERE id = $1)", message.channel.id
    ):
        await ban(
            message.author,
            reason=f"Sent a message in {message.channel.mention}",
            delete_message_days=1,
        )

TypeError: ban() got an unexpected keyword argument 'reason'

steep estuary
#
@bot.command()
async def react(ctx, chat:discord.Message.id, emoji:discord.Emoji):
    if chat is not None:
        if emoji is not None:
            message = int(chat)
            await message.add_reaction(emoji)
        else:
            await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")  
    else:
        await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
```this is not working
#

:/

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member 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.

steep estuary
#
@bot.command()
async def react(ctx, chat:discord.Message.id, emoji:discord.Emoji):
    if chat is not None:
        if emoji is not None:
            message = int(chat)
            await message.add_reaction(emoji)
        else:
            await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")  
    else:
        await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
```this is not working pls help :/
hasty loom
#

literally read above

#

oh wait its a differnet guy

#

apologies lol

steep estuary
#

:/

hasty loom
#

oh wait no it is the same guy

steep estuary
#

it is not reacting

#

??

cyan bay
#

i have a question

lament mesa
cyan bay
#

you guys know how dank memer posts memes if you type "pls meme", right?

lament mesa
#

yes

cyan bay
#

well, i tried doing that, but it only posts the URL, not the image

lament mesa
#

it uses the reddit api

hasty loom
#

does it have embed perms

#

and is the url a direct url to the image

cyan bay
cyan bay
hasty loom
#

yeah that wont work

#

its just gonna send the post

cyan bay
#

ahhhhhhhhhhhh

lament mesa
#

You can send requests to the api or use an api wrapper (like asyncpraw)

cyan bay
#

thanks, ill try it out and tell u if it works

hasty loom
#

purge_limit=number

lament mesa
#

channel.purge

steep estuary
#

help pls

#

i made a command >react [msg id] [emoji] it is only reacting the server emojis but it is showing emojinot found error in inbuilt emojis :/

visual island
hasty loom
steep estuary
#

help pls
i made a command >react [msg id] [emoji] it is only reacting the server emojis but it is showing emojinot found error in inbuilt emojis :/

visual island
#

in the way before you're making a recursive function

slate swan
hasty loom
# visual island `await message.guild.ban(...)`

ok so just

@bot.listen("on_message")
async def ban(message):
    if await bot.db.fetchval(
        "SELECT EXISTS (SELECT id FROM banchannels WHERE id = $1)", message.channel.id
    ):
        await message.guild.ban(
            message.author,
            reason=f"Sent a message in {message.channel.mention}",
            delete_message_days=1,
        )
```?
steep estuary
#

pls help me :/

steep estuary
proper acorn
keen talon
visual island
unkempt canyonBOT
#

Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of which coroutine is being run is switches periodically to allow all of them to run, giving the appearance of running at the same time. This is different to using threads or processes in that all code is run in the main process and thread, although it is possible to run coroutines in threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function this would have raised an exception like: SyntaxError: 'await' outside async function

To run the top level async function from outside of the event loop we can get an event loop from asyncio, and then use that loop to run the function:

from asyncio import get_event_loop

async def main():
    await something_awaitable()

loop = get_event_loop()
loop.run_until_complete(main())

Note that in the run_until_complete() where we appear to be calling main(), this does not execute the code in main, rather it returns a coroutine object which is then handled and run by the event loop via run_until_complete().

To learn more about asyncio and its use, see the asyncio documentation.

proper acorn
#

Can you teach me the "await" and "async def"?

hasty loom
# proper acorn Can you dms and teach me "await" and "async def"?

i cant teach you but this man can https://www.youtube.com/watch?v=nFn4_nA_yk8

#python #asyncio #aiohttp
Python, asynchronous programming, the event loop... what is all this stuff?

We learn what python is doing in the background so we can make more API Calls faster. We learn how to go from requests to aiohttp in our code, and refactor code for asynchronous programming.

✍️Medium Post: https://betterprogramming.pub/pytho...

β–Ά Play video
steep estuary
#
@bot.command()
async def react(ctx, chat:discord.Message, emoji:discord.Emoji):
    if chat is not None:
        if emoji is not None:
            message = chat
            await message.add_reaction(emoji)
        else:
            await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")  
    else:
        await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
#

@keen talon

#

:/

lone aurora
#
@client.command()
async def memetest(ctx):
    variable = [
        'test',
        'test2',
        'test3']
    await ctx.send(random.choice)
``` anyone who could tell me what i might be missing ._.
keen talon
proper acorn
#

Can i do the normal def instead of async def in discord bot libraly?

steep estuary
#

:/

#

do u mwan i should remove discord.emoji?

keen talon
#

try removing it once

steep estuary
#

kk

slate swan
steep estuary
#

ooo done thx :)

lone aurora
#

how can one be so smort

steep estuary
#

@keen talon

slate swan
keen talon
lone aurora
#

end me now

#

yooo it works

#

yaall geniuses

slate swan
#

read how random module works. its simple

proper acorn
#

Ummm i cant understand

#

We using "await" for input parameter in async function right?

lament mesa
#

by channel i meant the instance

#

ctx.channel.purge will also work

#

limit=amount

#

its a kwarg

final iron
#

Are there any good alternatives to asyncpraw

#

I'm having a lot of issues with it

#

Nope

#

It's not like a coding issue

#

It's the documentation and the fact it's extremely slow

pale turtle
#

Asyncpraw and SQL? How are these even related?

#

Oh lol

final iron
#

So you know any?

#

It's extremely slow

#

Bots like dank memer can render in images in like a second

#

Idk how they manage to do it

#

What are you doing with it?

#

What's the post limit?

stark bobcat
#

Is there any good api or module for making a chat bot?

final iron
#

You're grabbing the top posts right?

#

There should be something like limit=

#

I think

static patio
#

well how to fix this? and dw api key is wrong

final iron
#

Can you send the code?

#

It's 3 am for me rn

slate swan
keen talon
#

!decorators

unkempt canyonBOT
#

Decorators

A decorator is a function that modifies another function.

Consider the following example of a timer decorator:

>>> import time
>>> def timer(f):
...     def inner(*args, **kwargs):
...         start = time.time()
...         result = f(*args, **kwargs)
...         print('Time elapsed:', time.time() - start)
...         return result
...     return inner
...
>>> @timer
... def slow(delay=1):
...     time.sleep(delay)
...     return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!

More information:
β€’ Corey Schafer's video on decorators
β€’ Real python article

heavy folio
#

how do i get number of bans from a server

#

i did len(ctx.guild.bans)
and it said typeerror
and when i tried await ctx.guild.bans() and await ctx.guild.bans it returned some error too

slate swan
tough mesa
#

how does one take a member as a command perameter but handle the error if they type an invalid user?
e.g. -ping Joshalot is fine but -ping Joshanot will raise an error

#

right now i have this ```py
async def add(ctx, user: discord.Member = None):

vagrant brook
spring flax
vagrant brook
#

So you have to await it

slate swan
#

oh right yeah

tough mesa
slate swan
#

or for the command specifially if you wish

vagrant brook
#

Maybe try command.error decorator

spring flax
slate swan
#
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MemberNotFound):
    #code
#

This'll be a global command handler (not for a specific command)

tough mesa
#

thank you sm, i didnt know about that

heavy folio
spring flax
slate swan
#

probably consider going through that if you need more sight on eh

slate swan
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.

heavy folio
#

also

#
  tc = len(ctx.guild.text_channels)
  vc = len(ctx.guild.voice_channels)

  if tc is None and vc is None:
    pass
  elif tc is None and vc is True:
    new_embed.add_field(name="Channels:", value=f"![channel_voice](https://cdn.discordapp.com/emojis/883254153533591573.webp?size=128 "channel_voice") {vc}")
  elif tc is True and vc is None:
    new_embed.add_field(name="Channels:", value=f"![channel_text](https://cdn.discordapp.com/emojis/883254153789448232.webp?size=128 "channel_text") {tc}")
  elif tc is True and vc is True:
    new_embed.add_field(name="Channels:", value=f"![channel_text](https://cdn.discordapp.com/emojis/883254153789448232.webp?size=128 "channel_text") {tc}\n![channel_voice](https://cdn.discordapp.com/emojis/883254153533591573.webp?size=128 "channel_voice") {vc}")

also i did this and it didnt work i forgot how to use damn operators lol

slate swan
#

what

heavy folio
# slate swan what

i want it such that if tc is 0 then do this, else if vc is 1 and above it will do that

slate swan
#

uh..

#

> < >= =<

#

==

#

i mean you are checking length, so it'll return numbers

heavy folio
#

okay ty

slate swan
#

=

#

mb

vagrant brook
#

Not sure but if you're deleting multiple messages better use purge

slate swan
#

Hey, can somebody help me with my welcome message? Its not working, theres no error and intents are enabled

#

they are not working, thats the problem

lone aurora
#

hello

#
@client.event
async def on_member_join(member):
    channel = client.get_channel(883265182237880340)
    await channel.send(member.mention + " has joined.")``` this code was working a moment ago
#

but now i changed the channel and its not working

#

the bot has perm to send msgs in the channel

#

actually it can pretty much do anything it wants in the channel

#

they are

#

and i enabled the settings from dev portal

#

and the kick/ban/leave msgs are showing

river kindle
#

hey guys i created a mute system, but it doesn't work

here the code:

@ commands.has_permissions (manage_messages = True)
async def mute (ctx, member: discord.Member, *, reason = None):
  if reason == None:
    await ctx.send ('Enter a reason to mutate!')
    return

  guild = ctx.guild
  muteRole = discord.utils.get (guild.roles, name = "Mutato")

  if not muteRole:
    await ctx.send ("The role for the Mute does not exist. Creating ...")
    muteRole = await guild.create_role (name = "Mutato")

    for channel in guild.channels:
      await channel.set_permissions (muteRole, speak = False, send_messages = False, read_messages = True, read_messages_history = True)
    await member.add_roles (muteRole, reason = reason)
    await ctx.send (f "{member.mention} has been changed to {ctx.guild} | Reason: {reason}")
    await member.send (f "You have been changed to {ctx.guild} | Reason: {reason}")```


The spaces are created by discord^^
lone aurora
#

i think u used the same tutorial i ddi so

#

i can send u the code i used

river kindle
lone aurora
#

yea i did too

spring flax
#

That isn't efficient code

#

Also the bot construction has a case_insensitive kwarg

lone aurora
#

why it doesn't show a join msg

#

even though the code previously worked

slate swan
#

I don't understand

#

Send the code for that

lone aurora
lone aurora
#

nope

arctic vapor
#

how do i get teh content from an embed?

slate swan
#

do you have error handlers?

arctic vapor
#

like for a normal message, i do message.content

#

what if its an embed

frigid apex
#

hello guys my discord bot dont start on my linux server anymore, but it works local
idk what to do

#

line 30

slate swan
#

for example

slate swan
lone aurora
#

what do you mean?

slate swan
lone aurora
#

that im getting any errors? because im not

lone aurora
slate swan
#

no, it's whatever you defined bot constructor as

frigid apex
#

@lone aurora i will try

#

Ah @slate swan ur right

lone aurora
#

im noob

frigid apex
#

@slate swan do u know what i can do to fix this?

pale turtle
#

@slate swan long live those who put their dogs as their pfp

#

Double-ping lmao