#discord-bots

1 messages · Page 462 of 1

soft wind
#

tell me

hasty iron
#

nice attempt at hiding the id but we still see it

soft wind
hasty iron
#

ok stop shitposting

boreal ravine
reef shell
hasty iron
boreal ravine
#

nvm

soft wind
slate swan
#

lol

soft wind
#

broooooooooooo

hasty iron
#

but anyways i dont see why you want to do that

soft wind
#

@jaunty sparrow tell plz

hasty iron
#

just store the member id

lament mesa
#

no one can do anything with that id

hasty iron
#

and then use Guild.get_member

lament mesa
#

so its ok to show it

hasty iron
#

and then Member.mention

soft wind
#

it's custom

#

msg like .changewelmsg bla bla bla

hasty iron
#

oh

soft wind
#

so i

hasty iron
#

then use format

soft wind
#

need to put member mention

hasty iron
#

!d str.format

unkempt canyonBOT
#

str.format(*args, **kwargs)```
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces `{}`. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

```py
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
```  See [Format String Syntax](https://docs.python.org/3.10/library/string.html#formatstrings) for a description of the various formatting options that can be specified in format strings.
hasty iron
#

and pass in member=your_member

soft wind
#

u can't see it?

#

lemme code

#

dint got time to

lament mesa
#

yes

#

but why are you printing?

#

it will only print once after the class is declared

slate swan
#

guys

reef shell
#

how can i get unix timestamp from a datetime object?

slate swan
#

i have this code but it dont want to send the welcome msg in the channel


@bot.event
async def on_message_join(member):
    channel = bot.get_channel(885907606558871642)
    embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!") 
    embed.set_thumbnail(url=member.avatar_url) 
    await channel.send(embed=embed)

lament mesa
unkempt canyonBOT
#

datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").

Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.

For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:

```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
```   New in version 3.3.

Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
reef shell
#

on_member_join

#

lol

slate swan
#

ah

reef shell
#

not message

slate swan
#

i'm really dumb

reef shell
slate swan
#

x)

reef shell
#

LMAOO

#

ok then what's the issue

slate swan
#

like i'm trying to do a simple welcome message

maiden fable
unkempt canyonBOT
#

time.time() → float```
Return the time in seconds since the [epoch](https://docs.python.org/3.10/library/time.html#epoch) as a floating point number. The specific date of the epoch and the handling of [leap seconds](https://en.wikipedia.org/wiki/Leap_second) is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as [Unix time](https://en.wikipedia.org/wiki/Unix_time). To find out what the epoch is on a given platform, look at `gmtime(0)`.

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
slate swan
#

and like it dont send the message in the channel

maiden fable
#

!e
import time
print(time.time())

jaunty sparrow
unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

1631288065.1466405
maiden fable
#

Yups

reef shell
slate swan
#

yeah

reef shell
#

like send_message and embed_links

slate swan
#

he have administrator perms

reef shell
#

<t:1631288065:R>

maiden fable
#

Remove the point

soft wind
reef shell
#

mhm

soft wind
#

@hasty iron thx bro formats work

slate swan
reef shell
slate swan
#

no i dont think so

#

yeah

#

it dont

reef shell
#

that's unexpected

#

btw, does your bot have members intent turned on?

slate swan
#

nah

ionic wadi
#

@bot.command(pass_context=True)
async def meme(ctx):
embed = discord.Embed(title="", description="")

async with aiohttp.BotSession() as cs:
    async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
        res = await r.json()
        embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
        await ctx.send(embed=embed)

I dont get an error or an output

slate swan
#

pass_context

ionic wadi
slate swan
#

remove it completely

ionic wadi
#

I tried that either, didnt fix it.

slate swan
#

didn't say it would fix it, you just don't need it 👀

ionic wadi
#

Oh ok lol

slate swan
#

you probably can't set both of the title and description to nothing

#

in an embed

hasty iron
#

its not aiohttp.BotSession

#

wtf

#

!d aiohttp.ClientSession

unkempt canyonBOT
#
class aiohttp.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, version=aiohttp.HttpVersion11, ...)```
The class for creating client sessions and making requests.
ionic wadi
#

I put In an title, description, and changed It to clientsession but still no output

hasty iron
#

override the __init__ and pass in the message you want inside the super’s init

#

or you could just subclass

#

and pass in when you call the class

hasty iron
ionic wadi
#
async def meme(ctx):
    embed = discord.Embed(title="Mempie", description="Hier is wat oog vermaak... Vers van reddit.")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await ctx.send(embed=embed)```
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.

hasty iron
#

what

#

you’d override the init and once you call the class the init gets called

lament mesa
#

Your custom exception needs to be a subclass of any built in exception classes

hasty iron
#

no

#

of Exception

#

or anything else

lament mesa
#

no, any built in exception class (TypeError, Exception, BaseException, ...)

hasty iron
#

who subclasses BaseException

lament mesa
#

that was an example

ionic wadi
#
async def meme(ctx):
    embed = discord.Embed(title="Mempie", description="Hier is wat oog vermaak... Vers van reddit.")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await ctx.send(embed=embed)```

Anyone who understans why theres nothing
No error, no output
#

understands* I suck at apis lol

hasty iron
#

you’re not even using the api correctly

frosty prairie
#

where the textbook went

hasty iron
#

the reddit api requires authentication

ionic wadi
#

ah

hasty iron
#

what you’re using there is json endpoints you’re not supposed to use

lament mesa
#

the ratelimits for the json api are high

stuck flare
#

is this guide up 2 date?

willow vine
#

is there a way i can increase the width of an embed

hollow valley
#

Hi

slate swan
hollow valley
#

Hi

willow vine
#

how do i search for music and play

#

certain music

#

like the first video

#

i want name to be passed, not url

slate swan
valid galleon
#

can someone recommend a good tutorial about a d.py ticket system such that when you react to the message, it opens a new for the person and the mods to chat in? with mongodb

slate swan
boreal ravine
slate swan
lone lichen
valid galleon
#

i was actually confused about the db stuff so yeah

#

ig i'll find something which is about mongodb

slate swan
valid galleon
#

i can make the ticketsys myself, just need to see how mongodb works with py

lone lichen
valid galleon
slate swan
#

why are you using mongodb?

lone lichen
lone lichen
#

And It’ s fast w lots of data

slate swan
#

Guys it is possible to change the name of the bot with a command or not ? and if its possible how

lone lichen
slate swan
lone lichen
#

Or if u wanna make ur life hell u can use selenium to log into dev portal and change the name, but it gonna last long and It’ s dumb

slate swan
#

!d discord.Member.edit

unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
lone lichen
ionic wadi
#
async def on_member_leave(member):
    channel = bot.get_channel(858699731928219668)
    embed=discord.Embed(title=f"Jammer {member.name}", description=f"{member.name} is {member.guild.name} verlaten.... :sob: ") # F-Strings!
    embed.set_thumbnail(url=member.avatar_url) # Set the embed's thumbnail to the member's avatar image!
    embed.set_footer(text="Bot powered by @APotato#1900")
    await channel.send(embed=embed)```

I dont get an output or an error, why?
slate swan
#

its on_member_remove

lone lichen
ionic wadi
#

Oh thanks

shell wing
#
@bot.event
async def on_ready():
    print('The bot is logged in.')
    print('Ready!')
    print('Logged in as ---->', bot.user)
    print('ID:', bot.user.id)
    
    await bot.change_presence(activity=discord.Game(name=f"Start up"),
                              status=discord.Status.idle)
    await asyncio.sleep(60)
    await bot.change_presence(activity=discord.Game(name=f"@cadmus help"),
                              status=discord.Status.do_not_disturb)
    startTime = time.time()
    
@bot.command(pass_context=True)
async def uptime(ctx):
        uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
        embed = discord.Embed(colour=0xc8dc6c)
        embed.add_field(name="Uptime", value=uptime)
        embed.set_footer(text="<bot name>")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + uptime)  

Error

Ignoring exception in command uptime:
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 38, in uptime
    uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
NameError: name 'startTime' is not defined
valid galleon
#

btw can i use a library like tensorflow with d.py so i can make a chatbot which works in a specified channel?

slate swan
#

global startTime on on_ready
or better, make it a bot variable bot.variable = value
also dont do shit in on_ready since its triggered multiple times :(

valid galleon
#

prob not

#

right?

lone lichen
#

Like It can be made

valid galleon
valid galleon
#

im guessing its gonna be pretty hard

slate swan
#

but its hard and you should probably do a couple of easier projects first

slate swan
shell wing
lone lichen
slate swan
#

can I send my code here?

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

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

slate swan
#

if its bigger ^^

lone lichen
slate swan
#

no. I mean, are you in the middle of something?

willow vine
#

i want these 2 embeds to be of same width

slate swan
#

םל

#

why isn't it letting me to send my 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.

lone lichen
slate swan
#

but, that is the thing that do not work...

slate swan
#

use the same embed ds_kek
i doubt there is a good way to achieve what you want without hard coding it

slate swan
lone lichen
#

U cant just post whole ass code then ask ppl to figure out whats wrong w it

#

Yk?

slate swan
lone lichen
slate swan
#

A simple guide to getting help

In order for us to help, we need relevant information.

Have an error/issues? Provide the full traceback output. Show code around the error, and any relevant code.
Something happening different than expected? Explain what's expected, then compare to what is actually happening.

Keep in mind that we are not you, we cannot read your mind, and saying something like "My code doesn't work!" or "I have an error." or "This code is broken, why?" or "Can somebody help me?" gives absolutely nothing, and is just annoying. You must provide information that we need in order to look into whatever your question is.

As a courtesy to others, please refrain from pasting large codeblocks into chat. If it's big enough, you will annoy other users in the channel. Please use services such as https://hastebin.com/, https://gist.github.com/ or https://ghostbin.com/.

If you don't know Python, hop into testing and run ?tag lp. Without a solid knowledge in Python, we cannot properly assist you. Yes, it will take months. Coding isn't just gluing text together. It takes time and patience — months or years.

lone lichen
#

U posted whole command and said It’ s not working

#

In dpy server

slate swan
# lone lichen Like, u gotta post the part of code that is not working and tell ppl what u tryn...
    @commands.Cog.listener()
    async def on_message(self, msg):
        data = get_leveling_data()
        await create_leveling_acc(user, guild)
        xp = data[str(guild.id)][str(user.id)]["xp"]
        lvl = data[str(guild.id)][str(user.id)]["lvl"]
        to_the_next_lvl = data[str(guild.id)][str(user.id)]["to_the_next_lvl"]
        xp += 1
        print("test")
        if xp > to_the_next_lvl or xp == to_the_next_lvl:
            data[str(guild.id)][str(user.id)]["xp"] = xp - to_the_next_lvl
            data[str(guild.id)][str(user.id)]["to_the_next_lvl"] = round(to_the_next_lvl ** 1.02)
            data[str(guild.id)][str(user.id)]["lvl"] += 1
        with open("leveling.json", "w") as f:
            json.dump(data, f)
hasty iron
#

you cant

#

its on discord's side

#

you dont have any control over embed sizes unless you add more characters

willow vine
#

is there a way i can add invisible characters

hasty iron
#

there is a zero width space

willow vine
#

how do i do that

hasty iron
#

google it

willow vine
#

okay

steep estuary
#

for what overwrites_for is used?

hasty iron
#

for getting overwrites

slate swan
#

@hasty iron blanket can you help me here please? I'm trying to add bot into the dropdown but I keep getting error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() takes 2 positional arguments but 3 were given 3 were given for line view = DropdownView(self, bot)

#

Another question i need to unrank someone with a command like +unrank that removes him all his ranks

hasty iron
#

also the self argument is implicitly filled

#

of the init

#

yeah, why did you pass in self

#

just pass in bot

slate swan
#

Hmm, trying that

#

Thanks

#

I did that but I still get kind of the same error now

slate swan
hasty iron
slate swan
#

of course, make an error handler

#

and i don't think you should try it on yourself

#

if you are the server owner

hasty iron
#

self.add_item(Dropdown())

slate swan
#

Oh

hasty iron
#

i meant that

slate swan
#

hey so im making a antinuke bot right now, currently if you create multiple channels at the same time (using a nuker) it will only delete 1 or 2 channels, would anyone know how to delete all channels made in a certain time frame (eg. the last 5 seconds)

#

I see that, my bad

tulip pawn
#

Hey I'm trying to make a guess the number game and it works but when someone else message when im playing thres and error

@bot.command(aliases=["gtn"])
async def guess(ctx):
    number = random.randint(1,100)
    
    await ctx.send(f'guess a number between 1 and 100 \nYou have 5 tries')

    ng = 0

    while ng < 5:
        response = await bot.wait_for('message')
        guess = int(response.content)
        if guess == int(response.content):
            if guess>number:
                await ctx.send('try guessing lower')
            if guess<number:
                await ctx.send('try guessing higher')
            if guess==number:
                await ctx.send('you got the number')
                return

@bot.event
async def on_command_error(ctx,error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send("Put in all required arguments please")
    if isinstance(error,commands.errors.CommandInvokeError):
            await ctx.send("thats not a number, your game has ended")

i know the error handling is kinda dum but it works for now 👀

slate swan
#

to make sure the bot only responds to your message and no anyone elses

tulip pawn
#

how to add that

slate swan
#

return true if the author is command user and channel is the channel where command is used

#

make a function

#

^

tulip pawn
#

ohh ok thanks

maiden fable
#

or lambda PepeGiggleHehe

slate swan
#

or that, sure

tulip pawn
#

whats lambda

slate swan
#

that's what I knew would happen aPES_Giggle

#

just use what i said, both work

tulip pawn
#

okay thanks 😄

slate swan
#

guys i have this snipe code but it's not working idk why



@commands.command(name="snipe")
async def snipe(self, ctx: commands.Context):
        """A command to snipe delete messages."""
        if not self.last_msg:  
            await ctx.send("There is no message to snipe!")
            return

        author = self.last_msg.author
        content = self.last_msg.content

        embed = discord.Embed(title=f"Message from {author}", description=content)
        await ctx.send(embed=embed)

#

name argument of command() is useless

hasty iron
#

not really

slate swan
#

do you have any error or output?

hasty iron
#

what if you want symbols in your command name

slate swan
#

it's used to indicate the command name if you don't define the async def as the command name

slate swan
hasty iron
#

in this case what

slate swan
#

it's useless

#

it doesn't really matter in any case

hasty iron
#

what

slate swan
#

why it dont want to work :/

#

he can use it if he wants

hasty iron
#

did you understand what i said

slate swan
#

yes

hasty iron
#

you cant have symbols in function names

slate swan
#

but he doesn't...

hasty iron
#

are we talking generally?

slate swan
#

no

hasty iron
#

or his specific case

slate swan
#

yes

hasty iron
#

well then its just a preference

#

not useless

slate swan
#

the command

#

have you loaded the cog?

#

i think so

stiff nexus
#
    async def send_bot_help(self, mapping):
        ctx = self.context
        hel = []
        bot = ctx.bot

        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(colour))
        
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands()))),
            )
        await ctx.send(embed=embed)
```how do i do `await self.filter_commands(cmds, sort=True)` in **value*???
cloud dawn
stiff nexus
cloud dawn
stiff nexus
#

like now its sending help of cmd which the author cant use

#

its sending both usable and non usable

cloud dawn
#

!d discord.ext.commands.Command.can_run this function will help with that.

unkempt canyonBOT
#

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

Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") attribute. This also checks whether the command is disabled.

Changed in version 1.3: Checks whether the command is disabled or not
stiff nexus
#

idk how to use this

cloud dawn
#

Inside the function the command or context is passed.

stiff nexus
#

in the value or in the loop?

cloud dawn
#

It's a command attribute,

stiff nexus
#

i am not understanding

cloud dawn
#
allowed_cmds = await self.filter_commands(cmds, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
#

cmds refering to a list of all the bots commands.

stiff nexus
#

'owner' object has no attribute 'can_run'

cloud dawn
#

is owner a cog?

stiff nexus
#

ya i have a cog

cloud dawn
#

Try this ```py
allowed_cmds = await self.filter_commands(bot.commands, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)

frosty prairie
#

uh i am having problem with database and this bot .. kinda i cant explain

cloud dawn
#

Not in a for loop!

frosty prairie
#

eh

cloud dawn
cloud dawn
frosty prairie
#

yea i got that

#

idk i just started databases today and .. :/

cloud dawn
frosty prairie
#

uh just see the code

stiff nexus
cloud dawn
#

Okay what database are we dealing/ what module.

frosty prairie
#

msql.connector

cloud dawn
#

I'm familiar with that module

untold token
#

Ello panda

cloud dawn
#

Do you get an error?

cloud dawn
stiff nexus
#
Traceback (most recent call last):
  File "main.py", line 22, in <module>
    from help import HelpCommand
  File "/home/runner/Trust-
Traceback (most recent call last):
  File "main.py", line 22, in <module>
    from help import HelpCommand
  File "/home/runner/help.py", line 35
    embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
    ^
SyntaxError: invalid syntax
        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
        allowed_cmds = await self.filter_commands(bot.commands, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", allowed_cmds),
            )
        embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
        embed.set_thumbnail(url=bot.user.display_avatar)
        embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
        await ctx.send(embed=embed)
frosty prairie
# cloud dawn Do you get an error?
import discord
from discord.ext import commands
import mysql.connector

database = mysql.connector.connect(
    host="",
    user="",
    passwd="",
    database="testing")


cursor = database.cursor()

sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')
bot = commands.Bot(command_prefix='.')



@bot.command()
async def test(ctx):
    await ctx.send("Name")
    ans = await bot.wait_for('message')
    strans = str(ans.content)
    sql = f'INSERT INTO testing (name) VALUES (%s)'
    val = (strans),
    cursor.execute(sql, val)
    await ctx.send('added to database')

the first one without discord.py works and the second one.. it says added to database but doesnt show in database

untold token
#

Hmm

#

Btw this is blocking

frosty prairie
#

huh?

untold token
#

MySql is not asynchronous

frosty prairie
#

whats asynchronous..

untold token
#

This means if you make a large query , your bot will be blocked

cloud dawn
#

!async

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.

stiff nexus
frosty prairie
untold token
cloud dawn
untold token
#

This means your bot will not respond

frosty prairie
#

bot did ig..

cloud dawn
untold token
#

Until the request is completed

stiff nexus
frosty prairie
#

sad not getting anything

untold token
frosty prairie
cloud dawn
frosty prairie
#

just 1

cloud dawn
untold token
#

Yeah then its fine

frosty prairie
untold token
#

And val = (strans),

upbeat otter
#
Button(style=ButtonStyle.grey, Label="1")
```Why does this say `Button got an unexpected argument 'Label'`
untold token
#

That is wrong

frosty prairie
#

uh i had that used for str(ans) but it gave error i forgot to remove

cloud dawn
frosty prairie
#

uh?..

cloud dawn
frosty prairie
upbeat otter
cloud dawn
frosty prairie
cloud dawn
stiff nexus
maiden fable
#

@upbeat otter label should all be lowercase

upbeat otter
#

ohthenx

frosty prairie
#

..

maiden fable
#

...

frosty prairie
#

...

untold token
#

....

cloud dawn
frosty prairie
maiden fable
frosty prairie
#

..

upbeat otter
#

I thought my friends were weird, u guys started with the dot thing too 😂

stiff nexus
frosty prairie
#
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')

ok so this works

maiden fable
#

@frosty prairie what is the problem?

frosty prairie
#

it doesnt give error .. but it just says added to database and doesnt add

upbeat otter
#

to use buttons, i should import discord_components right?

cloud dawn
#
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
upbeat otter
frosty prairie
cloud dawn
maiden fable
frosty prairie
cloud dawn
maiden fable
frosty prairie
#

how

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

ans
maiden fable
untold token
frosty prairie
#

@cloud dawn how it worked waww

stiff nexus
frosty prairie
#

wait a well it didnt work sad

maiden fable
#

!e print(type(('1'))); print(type(('1', )))

unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

001 | <class 'str'>
002 | <class 'tuple'>
maiden fable
#

ah gotcha

cloud dawn
#

Yeah mysql.connector takes tuples not str

maiden fable
#

every module takes in tuples

frosty prairie
cloud dawn
#

me a postgre user no

frosty prairie
#

panda help

cloud dawn
#

You just told us it worked pithink

frosty prairie
#

i had the other code written too

#

like .. just adding to database

stiff nexus
frosty prairie
#

without async def

frosty prairie
cloud dawn
#

Like per cog list in a list?

frosty prairie
#

..

stiff nexus
#

u know how the default help cmd work?
its only send the help of cmd which can be used by the author
mine sends all cmd of the bot

cloud dawn
cloud dawn
stiff nexus
frosty prairie
# cloud dawn Need more info🐼

all ik is```py
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')

this works
```py
async def test(ctx):
    await ctx.send("Name")
    ans = await bot.wait_for('message')
    strans = str(ans.content)
    sql = f'INSERT INTO testing (name) VALUES (%s)'
    val = (strans),
    cursor.execute(sql, val)
    await ctx.send('added to database')

this doesnt(it executes added to database but doesnt actually add and returns no error)

stiff nexus
#

a normal member can see owner only cmds too

cloud dawn
frosty prairie
#

..

stiff nexus
# cloud dawn Can you send your current code?
        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
        allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", allowed_cmds)), 
            )
        embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
        embed.set_thumbnail(url=bot.user.display_avatar)
        embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
        await ctx.send(embed=embed)
frosty prairie
#

..

cloud dawn
frosty prairie
#

may i dm panda

stiff nexus
#

that appends the help cmd

cloud dawn
#

No sorry, we can solve it here, i'm thinking about both problems 😌

frosty prairie
#

oka..

cloud dawn
upbeat otter
#

So basically trying to make a calculator but whenever i try to click a button it says: Interaction failed, Here is the current code:

@client.command()
async def calc(ctx):
  m = await ctx.send(content="Loading Calculator")
  expression = "None"
  delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
  e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
  await m.edit(components=buttons, embed=e)
  while m.created_at < delta:
    res = await client.wait_for("button_click")
    if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
      expression = res.message.embeds[0].description
      if expression == "None" or expression == "An error Occurred":
        expression = ""
      if res.component.label == "Exit":
        await res.respond(content="Calculator Closed", type=7)
        break
      elif res.component.label == "←":
        expression = expression[:-1]
      elif res.component.label == "Clear":
        expression = None 
      elif res.component.label == "=":
        expression = cal(expression)
      else:
        expression += res.component.label
      f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
      await res.respond(content=None, embed=f, component = buttons, type=7)
#

if somebody can help plz

stiff nexus
# cloud dawn And why?
class HelpCommand(commands.HelpCommand):
    def __init__(self):
        super().__init__(
            command_attrs={
                "help": "Shows help about the bot, a command, or a category",
            },
            verify_checks=True,
        )

    async def send_bot_help(self, mapping):
        ctx = self.context
        hel = []
        bot = ctx.bot
        owner = bot.get_user(862906093373751337)

        for cog, cmds in mapping.items():
            if cog and await self.filter_commands(cmds, sort=True):
                hel.append(cog)

        embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
        allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
        for idx in hel:
            embed.add_field(
                inline=False,
                name=idx.qualified_name.title(),
                value=", ".join(map(lambda x: f"`{x}`", allowed_cmds)),
            )
        embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
        embed.set_thumbnail(url=bot.user.display_avatar)
        embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
        await ctx.send(embed=embed)
sharp surge
#

I'm trying to upload a png to discord

file=discord.File("content.png")
embed.set_image(url="attachment://content.png")
await ctx.send(file=file,embed=embed)

but I keep running into errors like:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: _request() got an unexpected keyword argument 'form'
stiff nexus
sharp surge
#

I can just use the file name...

frosty prairie
#

:/

slate swan
#

guys i want to do a command that counts the members like +members

#

i forgot how

vagrant brook
#

!d discord.Guild.member_count

stiff nexus
#

then idk

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

i khnow it's easy

frosty prairie
#

..

upbeat otter
vagrant brook
#

And use attachment://filename instead

cloud dawn
#

Then i will try and fix it.

slate swan
#

what is a new lib for discord

brisk helm
#

.

frosty prairie
#

:/

#

.

sharp surge
# vagrant brook I'm not sure but set filename kwarg in discord.File
file_lol = discord.File("content.png",filename="kwarg.png")
            embed.set_image(url="attachment://kwarg.png")
 await ctx.send(file=file_lol, embed=embed)

Still same error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: _request() got an unexpected keyword argument 'form'```
cloud dawn
upbeat otter
frosty prairie
#

uh..

pale turtle
#

Why member.id if the typehint is discord.Member object?

stiff nexus
slate swan
#

what is a new lib to replace\ discord.py

cloud dawn
slate swan
#

thank you

cloud dawn
frosty prairie
cloud dawn
stiff nexus
#

ok

upbeat otter
cloud dawn
pale turtle
#

!e

class A(Exception):
    def __init__(self, message, user_id: int):
        self.user_id = user_id
        return super().__init__(message)
raise A('donno', 123)
unkempt canyonBOT
#

@pale turtle :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 4, in __init__
004 | TypeError: object.__init__() takes exactly one argument (the instance to initialize)
pale turtle
#

Uh what

pale turtle
#

!e

class A(Exception):
    def __init__(self, message, user_id: int):
        self.user_id = user_id
        return super().__init__(message)
raise A('donno', 123)
unkempt canyonBOT
#

@pale turtle :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | __main__.A: donno
pale turtle
#

There I think that's it

frosty prairie
cloud dawn
# stiff nexus thx ❤️

known error? ```py
Traceback (most recent call last):
File "C:\Users\eboss\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\eboss\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\help.py", line 848, in command_callback
return await self.send_bot_help(mapping)
File "C:\Users\eboss\Documents\GitHub\spotipy\commands\help.py", line 141, in send_bot_help
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
AttributeError: 'Member' object has no attribute 'display_avatar'

cloud dawn
stiff nexus
#

mine is 2.0.0a

cloud dawn
pale turtle
#

!e

class A(Exception):
    def __init__(self, message, user_id: int):
        self.user_id = user_id
        return super().__init__(message)
try:
        raise A('donno', 123)
except A as error:
    print(error.user_id)

I think this might be what you need? @tawdry perch

unkempt canyonBOT
#

@pale turtle :white_check_mark: Your eval job has completed with return code 0.

123
stiff nexus
#

thats why u try ctx.author.avatar_url

cloud dawn
stiff nexus
#

sure

cloud dawn
#

If so you can just do bot.owner to get the id :)

stiff nexus
#

ya

steady flume
#

help pls

stiff nexus
cloud dawn
#

Also ```py
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]

stiff nexus
cloud dawn
cloud dawn
#

Try this```py
class HelpCommand(commands.HelpCommand):
def init(self):
super().init(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=True,
)

async def send_bot_help(self, mapping):
    ctx = self.context
    bot = ctx.bot
    owner = bot.get_user(862906093373751337)

    embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
    allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]

    embed.add_field(
        inline=False,
        name='test',
        value=", ".join(allowed_cmds),
    )
    embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
    embed.set_thumbnail(url=bot.user.display_avatar)
    embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
    await ctx.send(embed=embed)
#

oh prob error at idx.qualified_name.title()

#

Edited

stiff nexus
cloud dawn
#

That looks better

stiff nexus
#
value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands())))
cloud dawn
stiff nexus
#

i want the same format but like it should only show the cmds that can be involved by the author

stiff nexus
cloud dawn
stiff nexus
#

tell

cloud dawn
#

I will code it hold on...

slate swan
#

Hello guys how can i do a +dm that dms a member when i do it pls

cloud dawn
#

Still coding..

slow epoch
floral jacinth
#

this: tmp = tmp.strftime("%B %Y %H:%M:%S") await ctx.send(f"l'account di `{member}` è stato creato nel `{tmp}`")

make: l'account di Hik#9778 è stato creato in data: December 2016 22:57:26

how can i add the number as 26 December 2016 ?

stiff nexus
jaunty hamlet
#

What did you have to do if a @bot.event caused your code to break? (i.e your commands don't work etc)

slow epoch
#
@help.group()
async def page(ctx, number):

  page1 = ["Exercise 1","Exercise 2","Exercise 3","Exercise 4","Exercise 5","Exercise 6","Exercise 7","Exercise 8","Exercise 9","Exercise 10","Exercise 11","Exercise 12"]

  page2 = ["Stuff", "Stuffa", "Stufdsds"]

  page = "page" + number

  await ctx.send(page)

I know why this isn't working, but I don't know the solution

  1. What I expect it to do is print the variables page1 or page2 based on the page number the user input.

  2. The error is when I do page = "page" + number, they are considered as strings instead of a variable

cloud dawn
#
class HelpCommand(commands.HelpCommand):
    def __init__(self):
        super().__init__(
            command_attrs={
                "help": "Shows help about the bot, a command, or a category",
            },
            verify_checks=True,
        )

    async def send_bot_help(self, mapping):
        ctx = self.context
        bot = ctx.bot

        embed = discord.Embed(description=bot.description, color=discord.Color(0xffffff))

        for cog, commands in mapping.items():
            try:
                if cog.get_commands():
                    embed.add_field(
                        inline=False,
                        name=cog.qualified_name,
                        value=", ".join([f"`{command.name}`" for command in cog.get_commands() if not command.hidden and await command.can_run(ctx)]),
                        )
            except(AttributeError):
                # Error for if the cog is a cog but not quite a cog like Help
                pass

        await ctx.send(embed=embed)
stiff nexus
#

wait let me try

stiff nexus
cloud dawn
hasty iron
#

commands that aren’t inside a cog won’t appear with that help command

#

and why cog.get_commands(), you already have commands

#

and rather than checking for an attribute error, you could just check if cog is None

spare agate
#

I was using ```py

channel = ctx.channel

def check(msg):
return msg.content == 'confirmar' and msg.channel == channel

await client.wait_for("message", check=check)

await channel.clone(reason= "Nuke Channel")
await channel.delete()


Does anyone know how to fix? It was for a nuke command
dapper cobalt
potent vortex
dapper cobalt
#

discord.Guild.premium_subscribers returns a list of discord.Member. You can do await ctx.send(member.name for member in ctx.guild.premium_subscribers)

slate swan
#

await ctx.send('\n'.join(member.name for member in ctx.guild.premium_subscribers))

#

use that instead

dapper cobalt
#

Oh wait right.

slate swan
#

help?

spring flax
#

What's game

slate swan
spring flax
#

Looking at the error no it does not

slate swan
#

hmm ok i'm dumb

#

solve?

kindred epoch
slate swan
kindred epoch
#

i dont think i can

lusty swallow
#

can you post a snippet @slate swan

#

the line is too long too. Ever consider abiding the 20 year old rule (pep 8)?

slate swan
#

ive been trying everything but it doesnt work. How can i make the emojis in place?

#

does message.content no longer work?

slate swan
#

why?

#

I'm sorry I figured it out. i had message.contents

#

For some reason people can still tag roles even though i have it disabled in the channel permissions. can't figure out why. I've checked their permissions and roles as well

prisma wedge
#

hey so my bot has a covid command

#

for example

#

if it shows this number

#

482292

#

how do i make it so it puts the commas

slate swan
#

with

        if len(checks) < 10:
            for doc in range(len(checks)):
                mem = ctx.guild.get_member(checks[doc])
                name = mem.display_name()
                print(name)
        else:
            for doc in range(10):
                mem = ctx.guild.get_member(checks[doc])
                name = mem.display_name()
                print(name)```
I'm getting 
```File "/home/turtle/dusk-beta/cogs/economy.py", line 429, in baltop
    name = mem.display_name()
TypeError: 'str' object is not callable```
slate swan
slate swan
#

Anyone know how to get a print out of all permissions in a channel

#

if you want for a particular user

ivory drum
#

i want my program to tell me what message caused an error but this doesn't work and says the object "CommandNotFound" is not subscriptable py await kevlu8.send(error + " when command " + str(ctx.message) + " was run.")

slate swan
#

post full function

crude crater
#

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

crude crater
#
async def stats(self, ctx):
#

how dis an invalid syntax?

slate swan
#

show full code maybe

crude crater
#
@client.command()
async def stats(self, ctx):
        embed = Embed(title="Bot stats",
                      colour=ctx.author.colour,
                      thumbnail=self.bot.user.avatar_url,
                      timestamp=datetime.utcnow())

        proc = Process()
        with proc.oneshot():
            uptime = timedelta(seconds=time()-proc.create_time())
            cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user)
            mem_total = virtual_memory().total / (1024**2)
            mem_of_total = proc.memory_percent()
            mem_usage = mem_total * (mem_of_total / 100)

        fields = [
            ("Bot version", self.bot.VERSION, True),
            ("Python version", python_version(), True),
            ("D iscord.py version", discord_version, True),
            ("Uptime", uptime, True),
            ("CPU time", cpu_time, True),
            ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True),
            ("Users", f"{self.bot.guild.member_count:,}", True)
        ]

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=embed)
slate swan
#

removed every self in that code

crude crater
#
@client.command()
async def stats(ctx):
        embed = Embed(title="Bot stats",
                      colour=ctx.author.colour,
                      thumbnail=bot.user.avatar_url,
                      timestamp=datetime.utcnow())

        proc = Process()
        with proc.oneshot():
            uptime = timedelta(seconds=time()-proc.create_time())
            cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user)
            mem_total = virtual_memory().total / (1024**2)
            mem_of_total = proc.memory_percent()
            mem_usage = mem_total * (mem_of_total / 100)

        fields = [
            ("Bot version", bot.VERSION, True),
            ("Python version", python_version(), True),
            ("D iscord.py version", discord_version, True),
            ("Uptime", uptime, True),
            ("CPU time", cpu_time, True),
            ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True),
            ("Users", f"{bot.guild.member_count:,}", True)
        ]

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=embed)
slate swan
#

yes

crude crater
#

the "thumbnail=bot.user.avatar_url," says "positional argument follows keyword argument"

slate swan
#

cuz thumbnail isnt a argument in a embed its a method

hollow agate
#
            member = ctx.author
            em = discord.Embed(
                title=f"Suggestion",
                description=
                f"{reason}",
                color=0x00a8ff)
            em.set_author(name=f"{ctx.author}", icon_url={member.avatar_url})``` ```py
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
``` What am I doing wrong here?
crude crater
#

well what does your error say you're doing wrong?

hollow agate
#

member doesn't have avatar_url, but the docs tell me to use member?

#

Or user in that case

crude crater
#

try user then 🤷‍♂️

slate swan
#

surprisingly Member does have the avatar_url attribute

slate swan
hollow agate
#

Was just testing it, it shouldn't make an impact

crude crater
#

i didnt even see that lmao

#

im no expert but im pretty sure it does lol

hollow agate
#

I tested it many times and it gave me the same error as without the brackets so idk

hollow agate
crude crater
#

member = [what you want to define it as here lol]

slate swan
#

a discord.Member object

hollow agate
#
member = ctx.author``` Yes, no?
lusty swallow
#

that's seems correct

hollow agate
#

Same error :P

crude crater
#

why dont you just type out ctx.author? lol

hollow agate
#

Because that's the same error lol

crude crater
#

if thats what you want it to be

lusty swallow
#

try member.default_avatar.url

#

or even member.avatar.url

hollow agate
#
        else:
            member = ctx.author
            em = discord.Embed(
                title=f"Suggestion",
                description=
                f"{reason}",
                color=0x00a8ff)
            em.set_author(name=f"{ctx.author}", icon_url=member.default_avatar.url)``` Gives me the gray icon
slate swan
crude crater
#

what is this even for? userinfo command?

slate swan
hollow agate
#

Basically, yes

crude crater
#

ill just give you my code lol

#

if you want lmao

hollow agate
#

Sure, I can try it :P

lusty swallow
hollow agate
#

I've done everything the documents said, I'm on 2.0 so that could be a bug not sure though

crude crater
#
from datetime import datetime
from typing import Optional

from discord import Embed, Member


@client.command()
async def userinfo(ctx, member: Optional[Member]):
        target = member or ctx.author

        embed = Embed(title="User information",
                      colour=target.colour,
                      timestamp=datetime.utcnow())

        embed.set_thumbnail(url=target.avatar_url)

        fields = [("Name", str(target), True),
                  ("ID", target.id, True),
                  ("Bot?", target.bot, True),
                  ("Top role", target.top_role.mention, True),
                  ("Status", str(target.status).title(), True),
                  ("Activity", f"{str(target.activity.type).split('.')[-1].title() if target.activity else 'N/A'} {target.activity.name if target.activity else ''}", True),
                  ("Account Made", target.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
                  ("Joined Server", target.joined_at.strftime("%m/%d/%Y %H:%M:%S"), True),
                  ("Boosting?", bool(target.premium_since), True)]

        for name, value, inline in fields:
            embed.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=embed)
hollow agate
lusty swallow
#

wait really?

hollow agate
#

Yeah that's why I'm confused

lusty swallow
#

it should work tho.. hmm

hollow agate
#

Maybe a bug?

lusty swallow
#

try passing it to type

crude crater
#

bro thats so old!

slate swan
#

is it, it would make sense

lusty swallow
slate swan
#

lol

#

here is your solution then

crude crater
#

i have 3.9?

#

huh?

lusty swallow
hollow agate
crude crater
#

idk just try my code

hollow agate
#

not python 2.0 lol

crude crater
#

ohhhh

#

yeah im autistic my fault lmaooo

slate swan
crude crater
#

and if its the beta then it could be a bug

crude crater
slate swan
#

i think im dying from hunger

lusty swallow
#

@hollow agate
can you try

        else:
            member = ctx.author
            avatar = member.avatar.url
            em = discord.Embed(
                title=f"Suggestion",
                description=
                f"{reason}",
                color=0x00a8ff)
            em.set_author(name=f"{member.name}", icon_url=avatar )
```as a test
#

normally it should work

lusty swallow
hollow agate
#

My brain

slate swan
ivory drum
# slate swan post full function

ok here:

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Missing parameters! Run :help to see correct parameters. :kek: :emoji_37:')
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have permission to run this command. :thonk: :Supper:")
    else:
      guild = bot.get_guild(855275010556821524)
      kevlu8 = guild.get_member(458684594703695872)
      if kevlu8 == None:
        kevlu8 = guild.get_member_named("kevlu8#5240")
      try: 
        await kevlu8.send(error + " when command " + str(ctx.message) + " was run.")
        print(str(ctx.message))
      except:
        splitatchar = 2000
        one, two = error[:splitatchar], error[splitatchar:]
        try:
          await ctx.send(one)
          await ctx.send(two)
        except:
            mid1, mid2 = two[:splitatchar], two[splitatchar:]
            try:
              await ctx.send(mid1)
              await ctx.send(mid2)
            except:
              await kevlu8.send("Bro there's an error go check console")
              print(error)```
slate swan
#

this line is not whats causing the issue

#

check the traceback again

slate swan
ivory drum
#

yeah when someone runs a command that isn't missingrequiredargument or missingpermission, i want to get dmed by my bot telling me what the error is and what caused it, but the line py await kevlu8.send(error + " when command " + str(ctx.message) + " was run.") gives me an error, "unsupported operand types for commandnotfound and str" in str(ctx.message)

#

@slate swan

slate swan
#

your error was "CommandNotFound" is not subscriptable

#

and what it means is that you tried to use square brackets with some object that doesn't support it

slate swan
#

error[:splitatchar]

#

is the cause

#

most likely

ivory drum
#

alright i'll try getting rid of that

slate swan
#

error isnt a string

#

its an object

#

so you can't just slice it

#

with []

ivory drum
#

it works when i only do py await kevlu8.send(error)

ivory drum
slate swan
#

error = str(error)

#

put this somewhere at the top of the function

#

see if its fine now

ivory drum
#

thanks it works now

ivory drum
# slate swan see if its fine now

but it sends me this, how do i get the exact message that was sent? (for context i sent :e which isnt a command to trigger commandnotfound)

slate swan
#

how do i get the exact message that was sent?

#

did ctx.message not work?

ivory drum
#

no, it gives the above output

pliant gulch
#

ctx.message is the discord.Message object, you want the content attribute of said object

#

!d discord.Message.content

unkempt canyonBOT
ivory drum
#

oh, i see, thanks a lot

slate swan
#

use ctx.message.content

#

instead of ctx.message

#

as andy said

slate swan
#

yes

#

i know

#

I know that you know. lol

slate swan
#

so just dont print it

ivory drum
#

alright, i see, thanks

slate swan
#

you can still know which type of error is it

#

by using isinstance like you already do

#

for some types of errors

ivory drum
#

its working

#

thanks guys

ivory drum
# ivory drum its working

also i may seem stupid because it already has the command there but just in case there's a different error lmao

minor shoal
#

So I'm writing a discord bot for a server. One of them has 500+ users. The 2nd group (2 different bots) has over 6k users. I've heard about shards but can't really find the page in the wiki. Can someone give me a tl dr?

slate swan
#
req = await bot.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
# If statement because the user may not have a banner
if banner_id:
    banner_url = f"https://cdn.discordapp.com/banners/{user.id}/{banner_id}?size=1024"

how can i put this into a command

final iron
#

How would I make a command that sends how many times a certain word was said in a server

#

I know I have to check the message content

#

and use on_message but I just don't know how I would use that in a command

inland venture
#

@client(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = [
discord.Embed(title='It is certain.'),
discord.Embed(title='It is decidedly so.'),
TypeError: 'Client' object is not callable
i imprted client
weird

#

plz help

final iron
final iron
slate swan
#

could I get someone to make me a discord bot of my customs?

#

how do you remove a user's reaction on a message in the bot?

reef shell
#

!d discord.Message.remove_reaction

unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Emoji "discord.Emoji").

If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.

The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
reef shell
slate swan
#

ok thx

crude crater
#

how would i write aliases for a command

reef shell
#

@commands.command(aliases=["ali","ases"])

slate swan
reef shell
junior falcon
#

CommandNotFound error how i can get what command the user sent?

hollow agate
#

What's the best database to use?

junior falcon
hollow agate
#

How do I use it, like do I have to set it up on my pc or is it web-based?

junior falcon
hollow agate
#

?

junior falcon
#

?

hollow agate
#

Like do I download it and set it up on my pc so it uses my personal storage, or is it web-based and uses their storage?

junior falcon
hollow agate
#

Oh cool!

lunar grove
#

ok question

#

i have a ban command coded

#

it works with ids and mentions

#

but it doesnt work with ids of people not in the server

#
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
    await member.ban(reason = reasonlol)
    await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
#

any thoughts?

hollow agate
#

Nevermind

junior falcon
#

Why are u using has_any_role

#

if its just one role

lunar grove
#

because its universal

#

its not just for one server

junior falcon
#

ok

junior falcon
lunar grove
#

correct

grim oar
#

Use discord.Object

lunar grove
#

with a userid

grim oar
#

and pass it in Guild.ban

lunar grove
#

excuse me what

grim oar
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

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

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

`hash(x)` Returns the object’s hash.
grim oar
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
lunar grove
#

im still new to code and this just confused me more lol

#

i appolagise

reef shell
#

its fine

grim oar
#
obj = discord.Object(pass id here)
await Guild.ban(obj)
#

Guild has to be a discord.Guild object

#

like ctx.guild

reef shell
#

does this fetch the user even if the user is not in any mutual servers?

lunar grove
#

it should

lofty mulch
vagrant brook
grim oar
lofty mulch
#

Thanks you both

keen talon
grim oar
#

Yeah

slate swan
#

....

lunar grove
#
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
    obj = discord.Object(pass id here)
    await Guild.ban(obj)
    await ban(user, *, reason=reasonlol)
    await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
grim oar
#

Noo

slate swan
#

mo

#

no

#

the member is a int and the "pass id here" is suppose to be the member id

grim oar
#

^

#

You will have to edit the typehint

#

and Guild has to be a discord.Guild object, ctx.guild in your case

#

Remove that line below guild.ban too

lunar grove
#
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
    await ctx.guild.ban(obj)
    await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
grim oar
lunar grove
#

heck

grim oar
#

try
member: typing.Union[discord.Member, int] in your function arguments, then use isinstance to check if you got int or discord.Member, if int then pass it in discord.Object else pass member directly to Guild.ban

boreal ravine
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)...
boreal ravine
#

Typehint member to commands.MemberConverter and you'll be able to ban them using IDs, Mentions, Name#Discrim, name, Nickname. @lunar grove

vagrant brook
#

Typehint to discord.Member

grim oar
#

Not if they are not in guild

vagrant brook
#

Or discord.User

boreal ravine
boreal ravine
vagrant brook
#

That can take ID too

boreal ravine
#

o

ocean leaf
#

helllo guys, i asked for help in #help-bagel but MOnK told me to ask here.

#

i am getting this error

granite prawn
#

im thinking of making a discord.py invite tracker bot but i dont know where to start

ocean leaf
#

like make a list or int

granite prawn
#

i finished that

ocean leaf
#

ok now

#

@bot.event will do it

granite prawn
#

i want it to see who invited the user at on_member_join

#

and then i just get stuck

ocean leaf
#

idk much about these but in parenthesis i think we can pass the name of the variable user or joined member and we can use it

granite prawn
#

im asking of how to see who invited the user

ocean leaf
#

like on_member_join(ctx, user)

ocean leaf
granite prawn
#

yea but how in the world do i check who invited the user

granite prawn
ocean leaf
#

check tat out

#

there is a way

#

helllo guys, i asked for help in help-bagel but MOnK told me to ask here.
i am getting this error

granite prawn
#

just anyone who help me ping me here and tell me how to get user at on_member_join im gonna read the docs

#

i searched 'invite' at the docs and nothing helps me

ocean leaf
#

this may help

granite prawn
#

ill read it

ocean leaf
#

ok

slate swan
#

Hello

ocean leaf
slate swan
#

Whats the problem

#

You literally just showed me an error

#

Whats the code meant to do

ocean leaf
#

i am making a discord game like dank memer

#

making bank cmds

#

and using json database

#

and now i am getting this error

#

@slate swan

slate swan
ocean leaf
#

wait i am sending code

keen talon
reef shell
urban goblet
#

Hey, Im trying to help a streamer friend of mine. How would I make a bot that live reposts stuff from one channel into a channel on a diff server

ocean leaf
keen talon
untold token
keen talon
untold token
#

Postgres isn't for beginners

keen talon
#

Oh ok then

untold token
#

Mongo Db is fine too but if you want to start out with DBs you.can use aiosqlite3

ocean leaf
#

ok

#

thanks

lusty swallow
#

lmao

ocean leaf
#

having habbit

#

lol

lusty swallow
#

hobbit*

stark bobcat
#

how to use cogs

#

is there any tutorial on it

granite prawn
#

but then ill try

stark bobcat
#

thanks

#

do you know any video tutorials?

slate swan
#

theres this thing called youtube you should try it

kind tartan
#
import discord
import random


TOKEN = ''

client = discord.Client()

@client.event
async def on_ready():
    print('we have loggeed in {0.user}'.format(client))

    client.run(TOKEN)

In mine i have the token there ofc but the bot is not logging in why?

brisk fiber
#

you put your client.run(TOKEN) inside of your on_ready function, it needs to be outside

kind tartan
#

Thanks

brisk fiber
#

np, good luck!

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

frosty prairie
#

.

#

@cloud dawn

frosty prairie
late echo
#

help

vagrant brook
#

what is banned_users

late echo
#

idk i ssaw in youtube video

#

do you know how to

#

do

vagrant brook
#

Probably do something simpler to improve your python first 🙂

late echo
#

ok

vagrant brook
#

Anyway you can see there's no variable called banned_users previously in the code

late echo
#

what should i do then

maiden fable
late echo
#

yes

maiden fable
#

Don't

late echo
#

why

vagrant brook
#

Ya watching a tutorial youtube video and copying everything down isn't the way to learn

maiden fable
late echo
#

ok

dapper cobalt
late echo
#

i need unban

maiden fable
late echo
#

i know how to make a kick,ban and more.

#

i learned not copyed

#

he explained me

#

everything

maiden fable
#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
dapper cobalt
maiden fable
#

Ah

late echo
#

pls tell me a alternative

late echo
#

how to make a unban command

grim oar
#

get the Id of the person you are trying to unban and pass it in discord.Object(id here) then pass this object in Guild.unban

grim oar
#

No

late echo
#

what is worong in the code

#

pls tell pls

grim oar
#

that's a bad way of doing it

late echo
#

i did not understand

#

that

grim oar
#
obj = discord.Object(id)
await ctx.guild.unban(obj)
late echo
#

where should i put it

spring flax
grim oar
grim oar
#

Hmm then do that

maiden fable
#
user = discord.Object(I'd=I'd) 
await guild.unban(user=user) 

@grim oar

grim oar
#

👍

slate swan
grim oar
#

ye ^

lusty swallow
#

try this instead

frosty prairie
#

..

lusty swallow
#
    async def acceptapplication(self, ctx, message: discord.Message):
        guild = str(ctx.guild.id)        
        applicationchannel = self.bot.get_channel(self.applicationchannel[guild]['applicationchannel'])
        id = message.id        
        msg = await applicationchannel.fetch_message(id)
        applicant = msg.author
        await msg.reply(f"**Accepted.\nWelcome to the clan.**")
        await applicant.send("You have been accepted to the clan.")
#

@waxen granite

lusty swallow
frosty prairie
lusty swallow
#

partially

frosty prairie
#

uh ..

grim oar
#

Why are you fetching the Message, you already have it

lusty swallow
#

yeah why do you fetch it actually. Kinda curious too

#
    async def acceptapplication(self, ctx, message: discord.Message):
        guild = str(ctx.guild.id)        
        applicationchannel = self.bot.get_channel(self.applicationchannel[guild]['applicationchannel'])
        applicant = ctx.author
        await msg.reply(f"**Accepted.\nWelcome to the clan.**")
        await applicant.send("You have been accepted to the clan.")
frosty prairie
# lusty swallow partially
sql = 'INSERT INTO testing (name) VALUES (%s)'

val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')

this works

async def test(ctx):
    await ctx.send("Name")
    ans = await bot.wait_for('message')
    strans = str(ans.content)
    sql = f'INSERT INTO testing (name) VALUES (%s)'
    val = (strans),
    cursor.execute(sql, val)
    await ctx.send('added to database')

this doesnt(it executes "added to database" but doesnt actually add and returns no error)

#

..

frosty prairie
#

:/

lusty swallow
#

is that innodb?

frosty prairie
#

its mysql

lusty swallow
#

if so, you need to commit

#

yeah ik its mysql

#

check the engine

frosty prairie
#

how to check..

#

uh i google

lusty swallow
#

do you have phpmyadmin?

waxen granite
#

is there a way to send dm to a person whose name is on the embed.set_author?

lusty swallow
#

@frosty prairie just add this after the execution. <connection>.commit()

lusty swallow
#

wait no, can you elaborate?

waxen granite
#

well nvm, it is just complicated :3

lusty swallow
#

i mean you can but why?

lusty swallow
# frosty prairie oka..

make sure to replace <connection> with whatever variable you're using for the connection

actually nvm. sounds like you have myisam engine

lusty swallow
#

indent it and try it

frosty prairie
#

idk i just started with mysql..

#

uh oki

#

indent = tab?

lusty swallow
#

yeah

frosty prairie
lusty swallow
#

yeah i seperate mine from discord.py and make a module

#

wait

#

check this.
This is the module i use to simplify my code on mysql parts. I didn't finish it but it should work

frosty prairie
#

@lusty swallow it workeddd

lusty swallow
#

what did you do

frosty prairie
frosty prairie
lusty swallow
#

what?

frosty prairie
#

uh..

lusty swallow
#

ofc it's supposed to be included at the async

frosty prairie
#

why it worked..

lusty swallow
#

sounds like you have innodb engine too

frosty prairie
lusty swallow
#

consider installing phpmyadmin

frosty prairie
lusty swallow
#

wait let me check

frosty prairie
#

aighhtt

lusty swallow
#

@frosty prairie
SHOW TABLE STATUS WHERE Name = 'table'

lusty swallow
#

innodb requires committing changes

#

myisam dont tho. But innodb is still superior

frosty prairie
#

idk .. i c later

#

anyway thankss

distant tree
#

If anyone could help that'd be great.

frosty prairie
#

me noob but .. ask ig

#

I ITS BASIC

#

if*.