#discord-bots

1 messages · Page 553 of 1

stable delta
#

well... idk exactly what you mean for this question, but you could trigger typing

#

!d discord.abc.Messageable.trigger_typing

unkempt canyonBOT
#

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

Triggers a *typing* indicator to the destination.

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

i need help can anyone tell me the commnd for streaming

#

!avater

#

!avatar @unkempt canyon

slate swan
#

A bot application can't steam to a voice channel. @slate swan

round forum
#

Hihi

dusk pumice
#

It's too late but...

@bot.command()
async def Test(ctx):
  async with ctx.typing():
    await asyncio.sleep(1)
    await ctx.send("Done!")
#

Someone says it doesn't work, But it works!!!

#

Okay Okay... am I too late?

#

😐

blazing beacon
#

oh wait

#

fixed

cyan rover
#

can someone pls send a discord bot code for currency system

supple thorn
#

No

dusk pumice
boreal ravine
#

you just replied to yourself?

torpid dew
#

Hi, my first section works but my second section doesn't work, why is that?

@client.event
async def on_message(message):
    
  if message.author.id == ********: 
    await message.add_reaction(":Discordjs:")
  else:
    return 

@client.event
async def if_messsage(message):
    
  if message.author.id == ***********: 
    await message.add_reaction(":white_check_mark:")
  else:
    return 
boreal ravine
torpid dew
boreal ravine
#

also if_message isn't an event

torpid dew
boreal ravine
#

and check for multiple things

torpid dew
#

ok

boreal ravine
#

like if ... or ...:

torpid dew
#

ill try

#

thanks :)

boreal ravine
#

👍

torpid dew
boreal ravine
#

and whats the problem

viscid meadow
#

hhey i made dropdown menu but when i select any menu so it not chnage pls tell me whats wrong in my code

boreal ravine
#

check the status of the website

sick birch
#

can you elaborate? errors, what you expected it to do, what it's doing?

brave flint
#

hey, i wanna secure my tokens with .env, but i cant use dotenv so i used dotenvy. and because that i got error

slate swan
#

I can't get it to instant delete

valid perch
slate swan
#

like i want the message sent by bot to delete instantly

valid perch
#

So the one in the for loop?

slate swan
#

it sents @fallen gyro Catch +i i want this to be deleted instantly

#

await m.delete not working

valid perch
#

Well your not delting that message lol. You should set that equal to a variable then you can delete it
(Send returns the Message object to delete)

slate swan
#

didn't get it

#

just use delete_after kwargs of your send, set it to 0 if you want to delete it with no delays

#
s = response.content.split(" is ")[1].replace(".","")
      #response.delete()
      print(s)
      x = get_mon(s)
      #print(options)
      print(x)
      first_options = x
      for i in first_options:
        await message.channel.send("@ catch "+i)
      await m.delete()

can you edit it to be correct?
not a coder..

valid perch
#

!d discord.TextChannel.send

unkempt canyonBOT
#

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

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

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

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

Read le docs

slate swan
#

mmh

#

why is it saying my bot has an improper token wtf

valid perch
#

Because your using an invalid token

tiny pasture
#

yep

#

invalid token @desert rune

valid perch
#

Got an on_message?

valid perch
#

Care to show how you define bot

#

Sure, the bit you sent.

#

And how are you trying to call your command

brave flint
valid perch
#

@ is your prefix?

brave flint
#

uh

brave flint
#

that was for mentioning someone

brave flint
valid perch
#

And what makes you say that

brave flint
#

i got error when downloading dotenv on my pycharm

valid perch
#

Right

#

Well, if it works it works ig

brave flint
#

ok tq, i got the solution

fading harness
#

hi

#

how can i get info from a user, regarding that user in the server or not (by ping).

proud glade
#

what does that wikipedia api wrapper return as a result?

#

also, you prolly wanna do name="look" then add aliases 👍

proud glade
#

check em both out

#

!d discord.Member

unkempt canyonBOT
#

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

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/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/master/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/master/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.
proud glade
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
fading harness
#

and

#

how can i get user email?

spare creek
fading harness
#

that only account with email

spare creek
#

lmao ok i was jk

fading harness
#

ends with my school's domain

#

can verified

proud glade
#

that's private user information bud 👍

fading harness
proud glade
#

what

#

where did you get that

fading harness
#

from discord document

proud glade
#

hmm, smells like a selfbot only feature to me, otherwise i don't see how it would work

devout iris
#

How can i change bot status?

devout iris
#

Ty

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.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

viral pebble
#

how can I count the voice time that the users have done?

devout iris
#

Well, how can i set the bot status as "Watching"?

#

!d status

#

!d discord.Status

#

!d discord.Streaming

unkempt canyonBOT
#

class discord.Streaming(*, name, url, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord streaming status.

This is typically displayed via **Streaming** on the official Discord client.

x == y Checks if two streams are equal.

x != y Checks if two streams are not equal.

hash(x) Returns the stream’s hash.

str(x) Returns the stream’s name.
devout iris
#

Smh

slate swan
#
@bot.listen()
async def on_message(message):
  if message.author.id == 579353526371614743:
    return
  if message.content == 'hi':
    await message.channel.send("hello")

here how do i set like i want my bot to respond hello to hi but not just hi i mean like if the message sent is "hi i am kira"
bot still respond hello if it's "hi how are you" i want the bot to still respond hello i want it to respond hello if the message sent by the person contains "hi"
how do i do that

boreal ravine
#

bruh

#

what do you mean

#

I had a stroke reading that

slate swan
#

i want bot to respond hello everytime the message contains "hi"
the message sent by bot user

#

Me: hi how r u
bot:hello
me:Hi ok
bot:hello
me: hi (anything random)
bot:hello
like this

boreal ravine
slate swan
#

it's not working

boreal ravine
#

which aspect isn't working

#

just add a loop that loops through the message content

slate swan
#

even just plain "hi" isn't working

#

it's not responding

boreal ravine
#

again

boreal ravine
#

to check if the message

#

has a certain keyword

slate swan
#

how

boreal ravine
#

a for loop i guess

slate swan
#

what's the command

boreal ravine
#

what command?

slate swan
#

to loop

boreal ravine
#

you dont need a command to loop it

slate swan
#

then

boreal ravine
#

its basic python make a for loop that iterates through the message content

slate swan
#

uh how do you loop if no command

#

i don't know coding

boreal ravine
#

bruh

#

learn more python pls

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

yes i will can't in a day but

#

so can you help me here?

boreal ravine
#

im not gonna help you if you dont know what a for loop is sorry

slate swan
#
if message.author.id == 579353526371614743:
    return

it won't respond to this id? if i put it like this?

boreal ravine
#

its a return statement

slate swan
#

🤦 got it thanks smh some guy told me it'll only respond to this id if i put it there

slate swan
#

colorful @slate swan

reef shell
#

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

reef shell
slate swan
#
```py
msg
#

ok

#
i had made a code

boreal ravine
#

ok

slate swan
#

i want you to vew

#

it has to be python code

#

its a package

boreal ravine
#

!ot please if its not related to discord bots

unkempt canyonBOT
slate swan
#

i made it

reef shell
#

made what

slate swan
#

ok

devout iris
#
print("smh")
boreal ravine
#

ok

reef shell
#

#bot-commands

#

smh

slate swan
# unkempt canyon

Ngl i really really hate how discord made it so clicking channel mentions in embeds doesn't send you to that channel

boreal ravine
#

mobile?

slate swan
#

It used to be a thing before

#

Yes

boreal ravine
#

it wasn't a thing on mobile like ever

slate swan
#

It was

boreal ravine
#

only on pc

boreal ravine
slate swan
#

It used to be a thing on mobile last year

#

Ik bc last year I was using mobile a lot more often than I was using pc

final shard
#

Do we have to wait for slash commands to globally register?

slate swan
#

Yes

final shard
#

How long

slate swan
#

It can take up to 1h

final shard
#

Oh ok

lusty swallow
#

you can use guild commands for testing. it's instant

slate swan
#

^

final shard
#

I should've known that

lusty swallow
#

read the docs on how to turn it into a guild commands

final shard
#

Alright

viral pebble
#

I tried to convert datetime to float but I got this error, why?

lusty swallow
#

you can convert date time to float?

#

or did you mean timestamp?

slate swan
#

no

#

cantit is int

boreal ravine
slate swan
#

if you wanna convert to float

viral pebble
slate swan
#

i think better find other module

boreal ravine
slate swan
#

!e

unkempt canyonBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

boreal ravine
slate swan
#

!e ```py
type pip install pyartificialintelligence

boreal ravine
#

but I think you can't convert

#

a datetime object into a float

slate swan
#

yes

boreal ravine
slate swan
#

as datetime cant have

viral pebble
slate swan
#

floats

boreal ravine
slate swan
#

ill find something for you @viral pebble

boreal ravine
#

bruh

viral pebble
viral pebble
lusty swallow
#

!e

import datetime
print(datetime.datetime.utcnow().timestamp())
``` @viral pebble took me a long time lol
unkempt canyonBOT
#

@lusty swallow :white_check_mark: Your eval job has completed with return code 0.

1634973474.812864
lusty swallow
#

like this?

boreal ravine
#

no

boreal ravine
#

not a timestamp

slate swan
#

try this this would be better ```py
from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time) ```

slate swan
lusty swallow
#

well you can't convert a datetime object nor a string to float

slate swan
#

@viral pebble

boreal ravine
lusty swallow
#

i think he was doing this <t:12345:t>

boreal ravine
#

he wasnt

#

check his code again

lusty swallow
#

i meant his intention

#

there's not really much use of converting to float something other than dbms and timestamp

slate swan
#

how to see code output here

#

in this server

boreal ravine
#

how do you convert 00:00:00 to a float though

boreal ravine
viral pebble
lusty swallow
#

just subtract it

boreal ravine
slate swan
lusty swallow
#

it will return a datetime.delta

slate swan
viral pebble
boreal ravine
slate swan
#

datetime.now

slate swan
boreal ravine
boreal ravine
viral pebble
slate swan
boreal ravine
#

also stop trolling :|

boreal ravine
slate swan
slate swan
#

come to dm

boreal ravine
#

no

slate swan
#

shhewww

#

ok

viral pebble
lusty swallow
#

!e

import datetime
print((datetime.datetime.utcnow()-datetime.datetime.now()).total_seconds())
```Here's a sample. Python bot uses utc as timezone so it will be 0
unkempt canyonBOT
#

@lusty swallow :white_check_mark: Your eval job has completed with return code 0.

-4e-06
lusty swallow
#

@viral pebble ignore the part that says -4e-06

boreal ravine
#

it's already an int

#

you just can't convert it to a float thats all

slate swan
#

!e
from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | year: 2021
002 | month: 10
003 | day: 23
004 | time: 07:24:09
005 | date and time: 10/23/2021, 07:24:09
lusty swallow
unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
lusty swallow
cyan rover
#

!eval

#

!eval[print('how are you')]

lusty swallow
#

you don't need the []

cyan rover
#

thanks

lusty swallow
#

but do that in #bot-commands to prevent spam

cyan rover
#

ok

#

can you help to code a ban and unban command

#

@lusty swallow

lusty swallow
#

wym?

boreal ravine
lusty swallow
#

what's your code so far?

boreal ravine
#

we dont spoonfeed we help you

unkempt canyonBOT
#

Hey @cyan rover!

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

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

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

https://paste.pythondiscord.com

cyan rover
#

#bans player.
@client1.command()
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)

#unbans player.
@client1.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")

for ban_entry in banned_users:
    user = ban_entry.user

    if (user.name, user.discriminator) == (member_name, member_discriminator):
        await ctx.guild.unban(user)
        await ctx.send(f'Unbanned {user.mention}')
        return
#

this is the code

cyan rover
#

i am using replit

boreal ravine
#

ok?

lusty swallow
#

so does that work|?

cyan rover
#

no

lusty swallow
#

why

cyan rover
#

i don't know

boreal ravine
#

bruh

#

did u even try the command??

lusty swallow
#

is there a traceback?

cyan rover
#

no

lusty swallow
#

then you didn t execute the command

cyan rover
#

but when i type ban @slate swan it not working

boreal ravine
#

u sure

cyan rover
#

yes

boreal ravine
#

show me how u did the command

cyan rover
#

yeah i will send a screen shot

boreal ravine
#
  1. Does your bot have permissions
  2. Is the any error?
  3. Did you try doing !ban @person#1234?
cyan rover
#

no i didn't try the 3 one

boreal ravine
#

u said u tried banninng though

cyan rover
#

not working

boreal ravine
cyan rover
#

yes it does

lusty swallow
#

if it's permission related, it should raise a permission error

#

the cog is not loaded maybe?

boreal ravine
#

it worked

#

@cyan rover does it have intents

lusty swallow
#

@boreal ravine what's your bot for that?

boreal ravine
cyan rover
#

no error

lusty swallow
#

the code eval for discord bots

#

is it open source?

unkempt canyonBOT
boreal ravine
#

yes it is

lusty swallow
supple thorn
boreal ravine
lusty swallow
#

ohh nice

unkempt canyonBOT
lusty swallow
#

i'll try it in my server ty

unkempt canyonBOT
#

Hey @cyan rover!

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

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

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

https://paste.pythondiscord.com

boreal ravine
#

@cyan rover just paste it at the link

unkempt canyonBOT
#

@cyan rover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

#

@cyan rover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

boreal ravine
#

hm

cyan rover
#

can i dm

boreal ravine
#

sure Ig

valid perch
#

Doubt it is

heavy folio
cyan rover
#

check

#

this

boreal ravine
boreal ravine
valid perch
#

Why do you have both a Client and Bot...

#

You never run Bot is the issue

#

You only run Client

#

Smh, remove Client and just use an instance of Bot

heavy folio
boreal ravine
valid perch
#

Read the code they linked

boreal ravine
#

he only has commands.Bot not the client

valid perch
#
client1 = commands.Bot(command_prefix = '.')

phrases = []
lol1 = ("unkn‎‎own")

client = discord.Client()

...
client.run()
supple thorn
#

He does

boreal ravine
#

wait there 2 thingies

valid perch
#

uh huh

boreal ravine
#

@cyan rover what @valid perch said only use 1 bot variable

cyan rover
#

so what do you mean

boreal ravine
#

why do you even have 2 lol

cyan rover
#

should i remove client1

valid perch
#

Get rid of client = discord.Client() and only use your client1

kind radish
#

Can anyone tell me why this spams once the time is reached and not sleep
I am new, sorry if the code is stupid
Thank You

from discord.ext import commands
from datetime import datetime, time, timedelta
import asyncio

WHEN = time(7, 0, 0)

class Geyser2(commands.Cog):  
    def __init__(self, bot):
        self.bot = bot
        bot.loop.create_task(self.geyser_task())

    async def call_geyser(self):
        await self.bot.wait_until_ready()
        embed = discord.Embed(
            title=f"**Geyser will be up in 10 minutes**",
            description=f"_This message will self destruct once Geyser ends_",
            color=0xE2B1C8
        )
        embed.set_image(
            url="https://c.tenor.com/iZfN5AJ6NZEAAAAC/sky-sky-children-of-the-light.gif"
        )

        channel = self.bot.get_channel(865581332737294336)
        await channel.send(content=f"**TIME TO RUNNNN** <@&865992483351822356>", embed=embed, delete_after=1200.0)

    async def geyser_task(self):
        now = datetime.utcnow()
        if now.time() > WHEN:
            twohours = datetime.combine(now.date() + timedelta(hours=2), time(0))
            seconds = (twohours - now).total_seconds()
            await asyncio.sleep(seconds)
        while True:
            now = datetime.utcnow()
            target_time = datetime.combine(now.date(), WHEN)
            seconds_until_target = (target_time - now).total_seconds()
            await asyncio.sleep(seconds_until_target)
            await self.call_geyser()
            twohours = datetime.combine(now.date() + timedelta(hours=2), time(0))
            seconds = (twohours - now).total_seconds()
            await asyncio.sleep(seconds)

def setup(bot):
    bot.add_cog(Geyser2(bot))```
viscid meadow
#

plss help i am not getting how to make dropdown for my help command

valid perch
supple thorn
#

Replace client1 eith bot

#

Damn that discord lag

cyan rover
#

ok

kind radish
#

should be fine now

valid perch
#

Also, why have you made all your commands in on_message lol. That's what the command extensions for tejaji

cyan rover
boreal ravine
#

bad way to unban someone

supple thorn
valid perch
#

Sadly we can't read minds

cyan rover
#

i changed client1 with bot

valid perch
#

Oh deary

supple thorn
#

Whats the error

valid perch
#

Tbh, can you just send the updated code?

boreal ravine
supple thorn
#

Did you replace every client1 with bot

cyan rover
#

yes

supple thorn
#

show your code

cyan rover
#

used ctrl f2 to replace all

cyan rover
cyan rover
boreal ravine
cyan rover
#

updated one

valid perch
#

Likely the fact they dont process commands

#

You need to do this

boreal ravine
#

hm

#

I think it's because of your on message

#

@cyan rover use bot.listen()

cyan rover
#

if you can pls can you edit the could and send it

cyan rover
#

ok

boreal ravine
#

edit your bot.event decorator

#

to bot.listen()

cyan rover
#

ok

valid perch
#

You got linked something that explains it

cyan rover
#

not working

boreal ravine
#

BRUHHHHHHHHHHHHHH

cyan rover
valid perch
#

Yea, I'm just gonna say copy this and spell shit right

cyan rover
#

sorry

#

this is the error

#

@boreal ravine

valid perch
#

Cos you didnt spell it right

boreal ravine
unkempt canyonBOT
#

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

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

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

listen, not lisent

boreal ravine
#

read the docs

valid perch
#

Read what we have given you lol

boreal ravine
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").

Example...
boreal ravine
#

READ THE DOCS

slate swan
#

@bot.listen not lisent

valid perch
#

Lol what would we know

cyan rover
#

ok sorry lamo

#

still not working

valid perch
#

Why did you make your commands listen?

slate swan
#

Because commands should be @bot.command and not @bot.listen KEKL

valid perch
cyan rover
#

ok

cyan rover
#

i have to leave

slate swan
#

Look at this

cyan rover
#

i will try and get back

valid perch
#

Adios 👋

slate swan
#

Hi adios amigos

valid perch
slate swan
#
@bot.command()
async def test(message):
    await message.send("Done!")
    await asyncio.sleep(2)
    await message.delete()```

`discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'delete'`

I want the bot to delete its message after 2 seconds
manic wing
#

you've mixed bot.event with bot.command

slate swan
#

and? i can't?

manic wing
#

in a bot.command() you pass the parameter ctx

#

not message, but you can get message by ctx.message

#

ctx is an instance of discord.Context which has information such as ctx.command, and ctx.prefix.

#

message -> discord.Message

valid perch
#

ctx.message.delete

manic wing
#

that is a possibility but maybe not exactly what he wants

slate swan
valid perch
#

m = await message.send(..) await m.delete()

manic wing
void dew
#

Does anyone here knows sql

manic wing
#

a bit

valid perch
#

Quite a few people most likely

void dew
manic wing
#

I'm sure many people can help you if you state your question.

valid perch
#

Oh there was a I need help behind it, not just a general question. Intriguing

manic wing
#

if you have an issue i'm sure people here or in #databases would love to assist.

void dew
#

So I asked

manic wing
#

as I said, I don't know that much sql but I am willing to help. And after you send your code more than one person can help.

void dew
# manic wing as I said, I don't know that much `sql` but I am willing to help. And after you ...
@client.command()
@commands.has_permissions(manage_guild=True)
async def levelsetup(ctx):
  if client.user != ctx.author:
    db = await aiosqlite.connect('expData.db')
    cursor = await db.cursor()
    await cursor.execute('''
              CREATE TABLE IF NOT EXISTS guildData(
              guild_id TEXT,
              user_id TEXT,
              exp TEXT
              )
              ''')
    await db.commit()
    
    cursor = await db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)", (ctx.guild.id,
    ctx.author.id, 1))
    await ctx.send("Levelling system successfully setup for this server")

    await db.commit()

if message.author.bot:
      return
      
    await client.db.execute("UPDATE guildData SET exp = exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
    cur = await client.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
    data = await cur.fetchone()

    if data is None:
      return

    exp = data[0]
    print(data)
    lvl = math.sqrt((int(exp))) / client.multiplier
        
    if lvl.is_integer():
      await message.channel.send(f"{message.author.mention} well done! You're now level: {int(lvl)}.")

      await client.db.commit()``` This is the code
#

Sending error wait

manic wing
#

I notice you did await message.channel.send in a command

#

do you mean ctx

void dew
#

This is the error

manic wing
#

data is a Nonetype, meaning you can't index it. Just remove the [0]

valid perch
#

fetchone is returning None because it failed to fine a value

void dew
valid perch
#

Which is weird, because you check that

#

The code you sent us isn't the one your running

#

...

#

The one you sent us should work fine haha

    if data is None:
      return
void dew
valid perch
#

Well the one you sent here looks fine, use it and see

void dew
manic wing
void dew
#

Basically the problem is the server which used levelsetup command my bot works perfect in that server but who didn't use levelsetup my bot not working in that and shows error

valid perch
#

You can add a print or something to prove it

void dew
valid perch
#

To yourself why its not working

#

Can you look at the database and check the value your tryna find exists

void dew
# manic wing that just means the check worked, and it is `return`ing.

And I have a doubt before I was not having levelsetup command. Everything was in on_message only and that time I had a line cursor.rowcount == 0: and that time it was working but when I split the code because of levelsetup command I had to remove that line as it showed error cursor is not defined

#

So maybe its because of that line

#

And just for on_message without levelsetup command the code was this ```py
@bot.event
async def on_message(message):
if not message.author.bot:
cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)", (message.guild.id, message.author.id, 1))

    if cursor.rowcount == 0:
        await bot.db.execute("UPDATE guildData SET exp = exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
        cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))```
#

And going on

valid perch
#

I mean, you could look at the database and confirm values are in there

#

But hey lemon_wumpus

void dew
#

These all things made me think its because of that line

#

I am correct ot not

#

I don't know

manic wing
#

just as a recomendation; I don't particularly know what is going on here, but you can do py if message.author.bot: return and this means that you don't need to pile on lots of indents.

slate swan
#
@bot.command()
async def test(ctx):

    msg = await ctx.send('done')

    await ctx.send(f"{msg}")
    await msg.delete()```

`IndentationError: unindent does not match any outer indentation level`
Where i have `IndentationError`?????
manic wing
slate swan
manic wing
void dew
manic wing
#

what?

#

you can do @client.listen('on_ready') async def estaListo():

thin kelp
#

I am trying to add multiple reactions to a message. Currently I am adding the reactions one at a time through a loop. I wanted to ask if there is a way to add multiple reactions at once?

#
  await search_query_sent.add_reaction(numbers[i])```
thin kelp
#

Got it. Thank you

manic wing
#

maybe you do @client.evento('on_message') async def estaListo

#

otherwise, I'm not sure.

rare saddle
#

What does this mean?

manic wing
#

great question.

#

something to do with a TimeoutError

fast tundra
#

Hello, can you help me to place an order in a discord bot that allows to put roles thanks to reactions under my message?

final shard
#

How can we broadcast messages through each commands?

#

Like when u click a reaction, another message gets edited or deleted

manic wing
#

idk...

#

you have some weird language one

final shard
void dew
manic wing
#

¯_(ツ)_/¯

fading harness
#

how much shards do you think it needs for a discord.py bot with 60 servers?

slate swan
#

0

boreal ravine
#

you don't needs shards that early

slate swan
#

you shard when you have over 1k servers

boreal ravine
#

^

fading harness
#

i sharded my bot with 3,1k shards 🤣

boreal ravine
#

nice

slate swan
#

¯_(ツ)_/¯

valid perch
#

You can modify the base library code

#

Like dpy internals

#

Go find where it calls on ready and change that

honest coral
#

How accurate should I consider the member cache?

#

such as client.get_user() vs await client.fetch_user()

maiden fable
#

Just second makes an API Call

#

I don't think there's any difference (at least I never had a problem with it)

valid perch
#

getuser uses the cache, fetch hits the api

#

99% of the time get is fine

maiden fable
#

Yups

honest coral
#

Oh ok

#

How often is the cache updated?

maiden fable
#

Whenever a member is edited

honest coral
#

Ah, ok thanks

rain olive
maiden fable
last tapir
#

i have a command that makes my bot be quiet for 10 seconds using synchronous time.sleep() but after the sleep ends, the bot responds to all commands sent during the sleep period (i know why this is happening, just looking for a fix) and this is not what i want. does dicsord.py have a list of send message taskts that i can loop through and task.cancel()?

#

please ping me if you respond

maiden fable
manic wing
#

for example:

@bot.command()
async def sleepBot(ctx):
  bot.sleep = True
@bot.command()
async def awakeBot(ctx):
  bot.sleep = False
@bot.check
async def respond(ctx):
  if bot.sleep and ctx.command.name != 'awakeBot': return False
  return True```
#

and with this, you can use an asynchronous wait to unsleep it. For example:

#
@bot.command()
async def sleepBotTimed(ctx, time:float):
  bot.sleep = True
  await asyncio.sleep(time)
  bot.sleep = False```
lusty swallow
manic wing
#

@maiden fable it can be useful if you have another instance of the bot running.

lusty swallow
# manic wing what?

you can avoid typing this if bot.sleep and ctx.command.name != 'awakeBot': return False line by putting it in on_message instead

manic wing
#

do you know what a check is?

lusty swallow
#

ohh wait it's a check lol

#

i didn't see the decorator

#

i read that as bot.command()

gloomy quest
#

How to make it so that the bot says like- Watching <number of members> members

#

and how do I substract the number of bots from it

lusty swallow
manic wing
gloomy quest
#

o thx

lusty swallow
#

wait, bot.users is a valid attribute?

gloomy quest
#

maybe its a new thing that discord decided to add lol

manic wing
lusty swallow
#

ohh it is. just found that out

unkempt canyonBOT
manic wing
gloomy quest
#

oh lol

last tapir
slate island
#
async def add(ctx):

        SPREADSHEET_ID = 'spreedsheetid'
        RANGE_NAME = 'A1'
        FIELDS = 2 

        # Restrict the command to a role
        # Change REQUIREDROLE to a role id or None
        REQUIREDROLE = None
        if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
            await ctx.message.channel.send('You don\'t have the required role!')
            return
    
      
        msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')
        else:
           
            await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"``` 


At the moment you can if you type "!add ," it submits with no fields. Is there a way with this code to make it so you have to have some info to the fields before it accepts so if i type "!add hey," it shouldnt accept same goes with "!add ," it should accept if it is: "!add hey, hey"
last tapir
#

Wait does the bot not respond if its status is sleep/offline?

manic wing
slate island
#

Anyone? ❤️

last tapir
#

I replied to the wrong person, sorry

last tapir
slate island
#

Nobody who can help a helpless soul who have spend hours trying to figure it out?

last tapir
#

Be patient man you asked 4 minutes ago

slate island
#

Sorry.

last tapir
#

Also you should edit the post and add "```py" code here and "```" at the end to get syntax highlighting

#

It makes the code easier to read

slate island
#

Wait I did do the Hey ?

slate island
boreal ravine
slate island
#

Let me do it.

boreal ravine
#

didn't u ask for help yesterday

#

i asked you if if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None: was valid syntax

slate island
#
@client.command()
async def add(ctx):

        SPREADSHEET_ID = 'spreedsheetid'
        RANGE_NAME = 'A1'
        FIELDS = 2 

        # Restrict the command to a role
        # Change REQUIREDROLE to a role id or None
        REQUIREDROLE = None
        if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
            await ctx.message.channel.send('You don\'t have the required role!')
            return
    
      
        msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')
        else:
           
            await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"```
#

It is valid. 😄

#

It doesn'

#

doesn't work the "py"

boreal ravine
#

you sure

boreal ravine
manic wing
#
@client.command()
async def add(ctx):

        SPREADSHEET_ID = 'spreedsheetid'
        RANGE_NAME = 'A1'
        FIELDS = 2 

        # Restrict the command to a role
        # Change REQUIREDROLE to a role id or None
        REQUIREDROLE = None
        if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
            await ctx.message.channel.send('You don\'t have the required role!')
            return
    
      
        msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')
        else:
           
            await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"
#

like this.

#

you make a new line after the py

slate island
#

Arhh okay!

last tapir
#

Wow actually readable now lol

slate island
boreal ravine
#

@slate island error?

slate island
fading harness
#

hi in discord.py i want to detect if a shard loaded itll log in the console that Shard loaded!

boreal ravine
slate island
last tapir
#

Like whats the problem with that code drace

boreal ravine
glass sail
#

how do i make a purge command

slate island
#

At the moment you can if you type "!add ," it submits with no fields (SHOULDNT SUBMIT WITH NO FIELDS). Is there a way with this code to make it so you have to have some info to the fields before it accepts so if i type "!add hey," it shouldnt accept same goes with "!add ," it should accept if it is: "!add hey, hey"

#

Basically the bot reads the "," if it has the decided amount of "," it accepts.

#

It shouldnt there has to be text you give the fields before it accepts.

boreal ravine
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
glass sail
manic wing
boreal ravine
slate island
#

So yeah.. any command or changes I can make to code so it has to have filled fields before accepting.

glass sail
boreal ravine
slate island
slate island
#

I mean to the current code.

boreal ravine
#

!e

def function(first, second, third, fourth):
  pass
``` something like this
unkempt canyonBOT
#

@boreal ravine :warning: Your eval job has completed with return code 0.

[No output]
boreal ravine
slate island
#

hmm im lost.

boreal ravine
#

commands are async functions but in discord

#

just add the parameters??

boreal ravine
slate island
#

have to have it done by today.

#

so im fucked. well thanks anyway ❤️

boreal ravine
#

👍

#

you should be learning python functions before making a bot to understand what the commands do/are

slate island
#

I know what a python function is. I just don't know how I would insert it into my bot without breaking it.

#

Thats all. So im lost. 😛

boreal ravine
#

its literally the same thing

last tapir
#

You should read up on discord.py documentation, it's pretty good

boreal ravine
#
async def command(ctx, name, *, content)

is the same as

def command(name, *, content): #without ctx
#

i dont know what you dont understand

slate island
#

i know, but how does that solve the issue that you can post "!add ," without adding info to the fields "!add hey, hey".

last tapir
#

Well you can catch the exception that is thrown when you try to call a function with wrong parameters and send a message saying the command needs parameters

boreal ravine
#

you can add multiple parameters and do that e.g

async def function(ctx, name, *, content):
  await ctx.send(f"You created a tag called {name}\nContent:{content}")
slate island
#

As you can see in the code. I don't think what you showed me solves that.. without completely changing the code.. i might be wrong though,

boreal ravine
#

hm

slate island
#
 msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')```
glass sail
#

I have made a purge command but I don't want it to delete a specific message.
Example:

Guitar: i am bored
Guitar: hello
Guitar: Hi (i dont want to delete this)
Guitar: !purge 1
``` This is what it should like after purging```
Guitar: i am bored
Guitar: Hi (i dont want to delete this)
manic wing
#

lambda

glass sail
opal pewter
manic wing
#

what do you want to keep and what do you want to delete.

#

be specific.

glass sail
manic wing
#

channel.purge(*, check=lambda m: m.id not in idlist)

glass sail
#

thank you

boreal ravine
slate island
#

Sorry if I have a hard time explaining what I want. Sorry.

manic wing
slate island
#

But thanks for trying ❤️

zenith zinc
manic wing
#

hint: pip install PyNaCl.

zenith zinc
#

ok bro i trying wait

#

Thankss

#

❤️ no homo

slate island
#

but a function would fix the issue I am having with that people can just post a , and the bot accepts it?

slate swan
#

hello what do you need help with @slate island

zenith zinc
#

thisfix?

manic wing
#

learn python. don't copy and paste code without knowing what it is. that is my solution.

zenith zinc
#

i make my bot

#

but music no

manic wing
#

you copy and pasted it all. don't act as if you wrote a tiny bit of any of it.

zenith zinc
#

i copy and paste

slate island
# slate swan hello what do you need help with <@!884352679814500352>
@client.command()
async def add(ctx):

        SPREADSHEET_ID = 'spreedsheetid'
        RANGE_NAME = 'A1'
        FIELDS = 2 

        # Restrict the command to a role
        # Change REQUIREDROLE to a role id or None
        REQUIREDROLE = None
        if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
            await ctx.message.channel.send('You don\'t have the required role!')
            return
    
      
        msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')
        else:
           
            await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"```


Trying to make this code work. Basically you can cheat the bot to submit the info to the google sheet by just typing: !add , 
Basically it looks at how many commas there are by the chosen FIELD amount. So if you have 2 its 1 comma.

So basically you can post !add , and it submits or you can type !add hey, 

I want it so it requires the fields to be filled before accepting and not the ,

I've been looking at it for a few hours, but find it hard to change without changing the code completely.
zenith zinc
#

why idk make music

last tapir
#

how do i temporarily suspend the asyncio event loop? "pasue" kind of

slate swan
slate swan
slate island
last tapir
slate swan
#
async def add(ctx, *args):
  for arg in args:
    print(arg)

this will print each argument the user passes

#

you can use args to do whatever you want later on

slate island
#

Arhhh.. so change this:

async def add(ctx):

to

async def add(ctx, *args):
for arg in args:
print(args)

slate swan
#

you don't need to iterate and print args

#

but you can, just to see the args

slate island
#

Yeah of course. Let me try 😄

slate swan
#

btw

#

I made a mistake there, you should print arg, not args

slate island
#

So:

@client.command()
async def add(ctx, *args):
  for arg in args:
    print(arg)

        SPREADSHEET_ID = 'idhere'
        RANGE_NAME = 'A1'
        FIELDS = 2 

        # Restrict the command to a role
        # Change REQUIREDROLE to a role id or None
        REQUIREDROLE = None
        if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
            await ctx.message.channel.send('You don\'t have the required role!')
            return
    
      
        msg = ctx.message.content[4:]
        result = [x.strip() for x in msg.split(',')]
        if len(result) == FIELDS:
        
            
            DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
            sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
            await ctx.message.channel.send('Your data has been successfully submitted!')
        else:
           
            await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
last tapir
#

your indentation is messed up

slate swan
#

yeah select everything below the print and hit shift+tab twice, for vscode that works for me

slate island
#

Like this:

@client.command()
async def add(ctx, *args):
  for arg in args:
    print(arg)

SPREADSHEET_ID = 'idhere'
RANGE_NAME = 'A1'
FIELDS = 2 

# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
    await ctx.message.channel.send('You don\'t have the required role!')
    return


msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:

    
    DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
    sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
    await ctx.message.channel.send('Your data has been successfully submitted!')
else:
    
    await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
slate swan
#

not like that either

#

hit tab once

slate island
#

I did do shift tab twice doe :p

#

@client.command()
async def add(ctx, *args):
  for arg in args:
    print(arg)

    SPREADSHEET_ID = 'idhere'
    RANGE_NAME = 'A1'
    FIELDS = 2 

    # Restrict the command to a role
    # Change REQUIREDROLE to a role id or None
    REQUIREDROLE = None
    if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
        await ctx.message.channel.send('You don\'t have the required role!')
        return

    
    msg = ctx.message.content[4:]
    result = [x.strip() for x in msg.split(',')]
    if len(result) == FIELDS:
    
        
        DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
        sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
        await ctx.message.channel.send('Your data has been successfully submitted!')
    else:
        
        await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
slate swan
#

thats inside the for loop though, do this

#
@client.command()
async def add(ctx, *args):
    for arg in args:
        print(arg)

    SPREADSHEET_ID = 'idhere'
    RANGE_NAME = 'A1'
    FIELDS = 2 

    # Restrict the command to a role
    # Change REQUIREDROLE to a role id or None
    REQUIREDROLE = None
    if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
        await ctx.message.channel.send('You don\'t have the required role!')
        return


    msg = ctx.message.content[4:]
    result = [x.strip() for x in msg.split(',')]
    if len(result) == FIELDS:

        
        DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
        sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
        await ctx.message.channel.send('Your data has been successfully submitted!')
    else:
        
        await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
#

indent size 4

slate island
#

Let me see what you did. 2sec

#

arhhh

#

Tab once on print(arg)

#

Right?

slate swan
#

and the for

slate island
#

Arhh okay! Let me try 😄

slate island
wicked quest
#

I dont fully understand how do you save an attachment 😅 i tried await attachmentname.save("some_name.mp4") but that didnt do anything, how can i use this as a file object (not discord.File but like local file)

slate swan
#

you can get rid of these

REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
    await ctx.message.channel.send('You don\'t have the required role!')
    return

by using

@commands.has_role(yourroleid)
slate island
slate swan
#

you can filter args by length

slate island
slate swan
#

you don't want anything shorter than 2 letters?

slate island
slate island
slate island
slate swan
#

I don't get what you mean but

slate island
# slate swan I don't get what you mean but

Atm in the code FIELDS is set at 2. Which means that it requires 2 fields to be filled to fit into 2 fields in the google sheet, but the "," count as an arg you said which means it fills 1 field? Then it broke what worked.

slate swan
#
blacklist = [','] # put everything you dont want to add here
args = tuple(filter(lambda arg: arg not in blacklist, args))
#

it wont add commas separately

slate island
#

Hmm im confused now because my code basically it setup to split the fields by using the ","

slate swan
#

you can add anything to blacklist,
blacklist = [',', 'pie'] won't add comma and "pie"

slate swan
last tapir
#

what is the correct way to implement prefix-less commands? check content of message in on_message() ?

slate island
slate swan
#

result is basically what you have as "args", its arguments separated by spaces and its a tuple

slate island
slate swan
#

command = !add 1 2 3
result = args = (1,2,3)

exotic bear
#

why do slash commands take so long to register

slate island
#

Okay thats cool and all, but basically my script has a limit of how many fields you can post.. as you can see I chose 2 fields which means if by how the default code work.. if I had 2 commas.. then it would give me a error.

slate swan
slate island
manic wing
#

do kwargs work in a command lol

slate swan
#

I showed you how to get multiple args, you need to change your code accordingly to make it work

exotic bear
#

how can i use guild_ids for slash command while testing, other than just putting it in and taking it out manually

slate island
boreal ravine
boreal ravine
#

Can anyone give me an example of the on_raw_message_delete event?

slate island
# placid skiff What are you tryin to do?

Trying to get my bot to not bug. Basically i can submit to the google sheet by using "!add ," without adding anything to the fields. It accepts because it reads the amount of "," since fields is at 2. It looks for 1 comma. 3 2 and so on!

That means I can submit to it by doing !add , and it should be !add hey, hey.

#

and if I make the field 1.. i can just type !add and it submits.

slate island
#

I am completely lost.. just been trying the last 20 minutes..

cinder horizon
#

how to keep multiple prefixes with prefixes.json thingy...

boreal ravine
#

What bot object?

hollow tide
#

Are there any promising looking d.py forks

kindred epoch
#

!pypi disnake

unkempt canyonBOT
kindred epoch
#

Supports everything in d.py with slash commands, context menus and apps

devout iris
#

how can i set the welcome message when someone comes to the server

slate swan
#

I've tried looking at the API reference, but I can't set channel permissions.
Please let me know if there is a site that explains it in detail.

boreal ravine
slate swan
#

Guys, how do I get the bot not to mention the roles that I will tell him? I don't want him to mention the role "Players"
code: ```py
@bot.command(name="whois")
async def whois(ctx,user:discord.Member=None):

if user==None:
    user=ctx.author

rlist = []
for role in user.roles:
  if role.name != "@everyone":
    rlist.append(role.mention)


date_format = "%a, %b %d, %Y %I:%M %p"
memberavatar = user.avatar_url
b = ", ".join(rlist)


embed = discord.Embed(color=0x2f3136,timestamp=ctx.message.created_at)
embed.set_thumbnail(url=user.avatar_url),
embed.set_author(name = f"{user.name}", icon_url = memberavatar)
embed.set_footer(text=f'Requested by - {ctx.author}',icon_url=ctx.author.avatar_url)

embed.add_field(name='Joined',value=ctx.author.joined_at.strftime(date_format),inline=True)
embed.add_field(name='Created',value=ctx.author.created_at.strftime(date_format),inline=True)

embed.add_field(name=f'Roles: [{len(rlist)}]',value=''.join([b]),inline=False)

await ctx.send(embed=embed)```
#

how i can do it?

boreal ravine
#

!d discord.on_member_join this? @devout iris

unkempt canyonBOT
#

discord.on_member_join(member)``````py

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

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
slate swan
#
@bot.command(name="whois")
async def whois(ctx,user:discord.Member=None):

    if user==None:
        user=ctx.author

    rlist = []
    for role in user.roles:
      if role.name != "@everyone":
        rlist.append(role.mention)


    date_format = "%a, %b %d, %Y %I:%M %p"
    memberavatar = user.avatar_url
    b = ", ".join(rlist)


    embed = discord.Embed(color=0x2f3136,timestamp=ctx.message.created_at)
    embed.set_thumbnail(url=user.avatar_url),
    embed.set_author(name = f"{user.name}", icon_url = memberavatar)
    embed.set_footer(text=f'Requested by - {ctx.author}',icon_url=ctx.author.avatar_url)

    embed.add_field(name='Joined',value=ctx.author.joined_at.strftime(date_format),inline=True)
    embed.add_field(name='Created',value=ctx.author.created_at.strftime(date_format),inline=True)

    embed.add_field(name=f'Roles: [{len(rlist)}]',value=''.join([b]),inline=False)

    await ctx.send(embed=embed)```
boreal ravine
devout iris
boreal ravine
#

i was talking to the other person lol

devout iris
#

is this event?

slate swan
boreal ravine
#

yes @devout iris

boreal ravine
#

like

if player in user.roles:
  #code
slate swan
boreal ravine
#

thats impossible

slate swan
#

so that the bot does not write this role*

boreal ravine
boreal ravine
#

use list.remove() for this one e.g

if player in ...:
  list.remove(player)
slate swan
#

Thanks I'll try it right now

boreal ravine
unkempt yacht
#

whats wrong with this code?

async def reactionroles(self, ctx):
  await ctx.invoke(self.bot.get_command("help"), entity="reactionroles")

@reactionroles.command(name="channel")
@commands.guild_only()
@commands.has_guild_permissions(manage_channels=True)
async def rr_channel(self, ctx, channel: discord.TextChannel = None):
  if channel is None:
    await ctx.send("You did not give me a channel, therefore I will use this one")
  channel = channel or ctx.channel
try:
  await channel.send("testing if i can send messages here", delete_after=0.05)
except discord.HTTPException:
  await ctx.send("I can not send a message to that channel! Please give me perms and try again.", delete_after=30)
  return

embed = discord.Embed(title='**Self Roles**')

desc = ""
reaction_roles = await self.bot.reaction_roles.get_all()
reaction_roles = list(filter(lambda r: r['guild_id'] == ctx.guild.id, reaction_roles))
for item in reaction_roles:
  role = ctx.guild.get_role(item["role"])
  desc += f"{item['_id']}: {role.mention}\n"
embed.description = desc

m = await channel.send(embed=embed)
for item in reaction_roles:
  await m.add_reaction(item["_id"])
  
await self.bot.config.upsert(
  {
    "_id": ctx.guild.id,
    "message_id": m.id,
    "is_enabled": True,
  }
)
await ctx.send("That should be all setup for you!", delete_after=30)```
#

it shows this error:

boreal ravine
unkempt yacht
boreal ravine
#

probably some indentation error

#

your command was like this from what i can tell

async def func(ctx):
  #code

await channel.send()
rose shale
#

Hii, i was trying to make a music bot using youtube dl , so is there a way to get the information of how much current song played like (0:40/3:53)

wide rampart
#

Hello due to hosting a website for specific reasons on a dynamic ip i need a way to open it, i have decided to use discord. however i need help.

Need message to return as http://00.00.00.00:2030

I have the ip worked out just dont know how to add the http:// and :2030 to the start and end of the ip

code for context

if message.content == "-staff":
        ip = requests.get('http://ip.42.pl/raw').text  # Gives the "public IP" of the Bot client PC
        await message.channel.send(ip)
brave flint
#

hello, i making a youtube music bots with youtube_dl . and i got error

#

*** discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found**

boreal ravine
#

you can't use a module without downloading it first

upbeat otter
#

Guys, how do I get the server id in the on_member_remove event?

brave flint
boreal ravine
#

!pypi ffmpeg

unkempt canyonBOT
brave flint
pliant gulch
#

You don't download ffmpeg through pypi

#

You install it like another program

boreal ravine
#

or that

upbeat otter
#

.....

boreal ravine
#

oops

upbeat otter
boreal ravine
#

python didn't delete that

brave flint
pliant gulch
#

Hosted on a VPS?

#

I'm assuming your VPS has some sort of package manager (if your on a linux server)

#

Just install it through your OS's package manager

brave flint
pliant gulch
#

Heroku has a build pack for FFMPEG iirc

slate swan
#

It does

#

I'm hosting my music bot on heroku too after all 😂

brave flint
slate swan
#

Forgot what the link was but you can find if you search for it

slate swan
#

member.guild.id @upbeat otter

upbeat otter
slate swan
#

Yw

visual island
#

you need to call super() on the __init__()

#

super().__init__(prefix)

#

not there

#

put it below your self.command_prefix = ...

#

and revert line 4 to the last code

slate swan
#
async def on_message(msg):
	print(msg.content)
	if client.user.mentioned_in(msg.content):
		emb = discord.Embed(title = "Hello!", description = "My prefix is ```sp!``` and the help command is ```sp!help```\nHave a great day!", color = 0x08bfea)
		await msg.channel.send(embed = emb)```
#

Why is this not printing msg.content?

visual island
#

.listen needs ()

#

@client.listen()

slate swan
#

How can i make the bot to send the embed to the quotes channel

#

@visual island thanks a lot!

boreal ravine
#

just define quote_channel

slate swan
#

@slate swan insert the channel id

boreal ravine
slate swan
#

Whats this error?

slate swan
#

ik about the bot.get_channel(channel_id) but i want when someone will setup quotes. then the bot send in the quotes channel a quote

boreal ravine
# slate swan

!e

message = "string"
if message.mention_everyone:
  print("worked")
``` this obviously wont work since message has no attr mention_everyone
unkempt canyonBOT
#

@boreal ravine :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: 'str' object has no attribute 'mention_everyone'
slate swan
slate swan
covert palm
#

on message event?

#

how do u set it real quick?

slate swan
#

wdym

covert palm
#

i need help

#
counter = 0


@bot.event
async def on_message(message):
    if message.author != bot.user and message.content.startswith("!vibe"):
        counter+=1```
#

gives me an error in counter

#

i need it to see that counter is set outside and change the value of it

floral jacinth
#

hello, a fast question
how to remove all roles of a member?

manic wing
manic wing
fading harness
#

hi how can i make slash command with spaces? im using cogs and discord-py-slash-command.

zinc geyser
#

Im using the on_member_join() event for my bot but I need the member (which is returned by default) and the guild they joined, though the guild isnt passed as a parameter

covert palm
#

my on_message event isnt working

#

what do i need to do?

manic wing
covert palm
#

not working

manic wing
zinc geyser
#

oh thx

#

Ok, new question. Is there a method like Permissions.all but for PermissionOverwrites

covert palm
#

@bot.command()
async def count(ctx):
    await ctx.send(f"Number of current !vibes: {counter}")

@bot.event
async def on_message(message):
    print(message.content.startswith("!vibe"))
    if message.content.startswith("!vibe"):

        global counter 
        counter+=1
        print(counter)
        return```
#

thats the code

#

its working the print and all, but when I try !count it doesnt work

#

its like on_message always works

covert palm
manic wing
manic wing
#
bot = commands.Bot(...)
bot.counter = 0

##

##

##

@bot.command()
async def count(ctx):
    await ctx.send(f"Number of current !vibes: {bot.counter}")

@bot.event
async def on_message(message):
    if message.content.startswith("!vibe"):
      bot.counter += 1
#

much easier, so much easier.

#

you still need await bot.process_commands(message)

covert palm
#

works

#

thank u so much man

manic wing
#

yes.

#

no problem.

slate swan
#

How can i make this a loop?

@bot.command(aliases=['setup quote'])
async def setup_quote(ctx):
  quote_channel = await ctx.guild.create_text_channel(name='quotes')
  await ctx.send('The channel with the quotes has been succesfully created')
  await ctx.send('`*Reminder : you can move the channel anywhere you want`')
  quote = get_quote()
  emb=discord.Embed(description=f"**{quote}**", color=discord.Color.random(),timestamp=ctx.message.created_at)
  emb.set_author(name=f"{ctx.author.name}", icon_url=f"{ctx.author.avatar_url}")
  emb.set_footer(text="Next quote in 1 hour")
  await asyncio.sleep(3.600)
  await quote_channel.send(embed=emb)
#

Whats wrong here?

slate swan
#

Halp

potent light
manic wing
# slate swan How can i make this a loop? ```py @bot.command(aliases=['setup quote']) async de...

ah, I have this. you're going to want to have 3 things:
a) a list of channel ids
b) a database to store the channel ids - it can just be a json file, but you probably want the bot to remember to send the quotes, even if you restart the bot.
c) a discord.ext.tasks.loop.
In this example I am going to show how you may want to do it, but I will not show it linked to a database. You can do that part yourself. My github project where I have done this is https://github.com/caedenph/jesterbot.

@tasks.loop()
async def quote(): 
  ### Get channel_ids from database here ###

  for chan_id in channel_ids:
      channel = bot.get_channel(chan_id)
      await channel.send(quote)

in this example there is channel_ids, which holds the channel ids, and tasks.loop which is discord.ext.tasks.loop

You can also link this to a command,

@bot.command()
async def setup_quote():
  #apend to database```
potent light
#

@slate swan to sum it up for you. You are using a @commands.command() decorator which basically makes the function callable through a command e.i: !setup_quote not a task loop.
What you need is a task loop not a command. For this, you gotta change @commands.command() to @tasks.loop(hour = 1) and import it from discord import tasks. Then you'll have to initialize it by adding setup_quote.start() on your def __init__(self, bot): function within the main class.

slate swan
#

😔

floral jacinth
#

i wish to remove all roles of a member
but using

  await member.remove_roles(role)```
but error occur because it see *everyone* too, how can skip it?
manic wing
floral jacinth
#

like that?

manic wing
slate swan
#

@manic wing@potent lightthanks guys

potent light
potent light
gaunt mortar
#

Hi hi, I'm using discord.py library, I'm currently working on a feature that checks every 10s if my minecraft server is still up and return a ping if its not, the thing is I planned to use a while loop for it but.. I can't use commands while he is looping

gaunt mortar
#

Shall I use a thread for the loop and it works ? Or is it more than that ?

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
manic wing
#

Like this;

gaunt mortar
#

Oh, didnt knew about it, gonna check this

gaunt mortar
#

thanks a lot

manic wing
#
@tasks.loop(seconds=10)
async def check():
  #check if minecraft is up
  if not up:
    await Arsene.send('Oh no, its offline!')```
gaunt mortar
manic wing
#

no problem, you can pretty much do my example but add in the check for minecraft being online.

gaunt mortar
#

Just wanna know, can you put a global variable like seconds=timer, and if you change the timer the seconds needed will change aswell?

manic wing
#

actually, to be honest i'm not sure.

#

I shall check.

slate swan
#

@manic wing

@tasks.loop(seconds=3600)
async def #name of the command here?
manic wing
slate swan
#

so what am i writing there

#

?

manic wing
#

whatever you want the function name to be.

slate swan
#

oh okay

#

im very confused with the loop xD

manic wing
#

don't be.

slate swan
gaunt mortar
# slate swan im very confused with the loop xD

If it can helps you, usually in Python the function name is something used to describe it shortly, with the library the name of the command is the function name if you're using the @raven peak decorator, here it's not the case

slate swan
#

oh

gaunt mortar
#

The loop is just used to run something in a regular interval (for example sending a message every hour), its not a command

manic wing
#

!d discord.ext.tasks.loop.change_interval @gaunt mortar you can use this.

unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

manic wing
#

it doesn't show up on documentation, but you can use it.

gaunt mortar
#

kk, thanks

brisk fiber
#

I have a command foo in a group bar. is there a way to alias the command such that I can invoke it without the group name? eg ?foo instead of ?bar foo

manic wing
brisk fiber
#

will look into it, thank you!

gaunt mortar
slate swan
#

hey so my discord bot code is starting to get very smooshed even with comments and i was wondering if i can add certain sections on the code into a different .py so for example i have 1 code called moderation.py and that was all my moderation commands and like another code called generator.py and that was generator commands but it still links into 1 bot

gaunt mortar
#

it just looks like its ignoring the loop

manic wing
manic wing
gaunt mortar
#

standard python packages would works too nah?

slate swan
gaunt mortar
manic wing
#

they each have the ```py
class DiscordTogether(commands.Cog):
def init(self, bot: commands.Bot):
self.bot = bot
...

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

#

instead of using @bot.command you use @commands.command. Instead of using bot you use self.bot. Instead of doing async def commandName(ctx): you do async def commandName(self, ctx):

#

and that is basically it

#

you also initiate the cog files in your main.py

#

bot.load_extension('filename'). Please note you do not load filename.py you just do filename.

#

this is often paired with py for file in os.listdir('./cogs'): bot.load_extension(f'cogs.{file[:-3]}') this loads every file in cogs dir. You might also want to consider adding an if statement to check for __pycache__, as that could raise an error.

gaunt mortar
manic wing
#

Cogs can:

  • help with organisation.
  • create auto-generated help commands.
  • save time with checks and invokes for specific groups of commands.
  • increase readability
  • provide process_commands for on_message
placid jay
#

Маняци я накой да ми даде някой script за ddos

unkempt canyonBOT
#

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

placid jay
#

ама аз не break-вам никво правило ве пич

#

кво ти има

gaunt mortar
final iron
#

We can't help with creating a DDoS script as it is illegal @placid jay

placid jay
#

NOno

#

аз съм хакер от 1338 измерение

manic wing
gaunt mortar
#

dw, its my bad not yours :p

gaunt mortar
manic wing
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

manic wing
#

I think you are supposed to speak english.

final iron
#

^

#

Probably has to do with moderation

gaunt mortar
#

I think he doesn't speak english fluently, just tried to help him :p

slate swan
#

then you can take it to dms

slate swan
#

I created a command that does embed and after I gave an error :(

#

How to resolve the error?

wary pollen
#

Ok