#discord-bots

1 messages · Page 464 of 1

boreal ravine
#

o

dapper cobalt
#

!d discord.TextChannel.history you can iterate through the messages sent in the ctx.channel or each channel in the guild (there's a limit to how many messages you can check, I think.) And check if the word is in the message.content.

unkempt canyonBOT
#

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

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

Examples

Usage...
final iron
#

Alr ill see how it goes

pliant gulch
#

Keep in mind 1-100 messages is an API call

#

So if you were to check 500 messages thats 5 API calls and so on

final iron
#

Why does that matter?

dapper cobalt
#

Rate limiting.

final iron
#

ah

pliant gulch
#

Because the ratelimits are somewhat high on this endpoint iirc?

dapper cobalt
pliant gulch
#

If I remember correctly

dapper cobalt
#

Ah.

final iron
#

I was planning on looking at the entire servers messages

#

Guess ill have to limit it then

pliant gulch
#

Just have on_message tracking words

#

Put it in a database and you won't need to do any API calls

dapper cobalt
#

And save it in a database.

tulip oracle
#

is there an api for new post reddit events?
i normally just use the raw json for reddit but i couldnt automate this my self for new post i dont think

leaden anvil
#

Ok is there a way to stop a command using another command like for instant if I am using /play I want to stop the command through /stop how would I do that ?

final iron
#

I basically know nothing about data bases and I host my bot locally so its barely ever online

tulip oracle
#

well a good time to learn

pliant gulch
#

You still should learn databases

final iron
#

Aight ig

#

What should I start out with

pliant gulch
#

Depending on how well you learn you can pick up sql in minutes probably

#

Afterwards since discord.py is asynchronous your gonna want to check out an async driver for whatever db you want to use

#

i.e postgres -> asyncpg, mysql -> aiomysql

final iron
#

alr

dusty stratus
#

can I make discord bots in python?

soft imp
#

help

#

how do they accept inite to test bot

final iron
covert igloo
slate swan
#

I'm so confused to why this command isn't working

    @commands.command()
    async def ping(ctx):
        await ctx.send('Pong')

discord.errors.ClientException: Callback for ping command is missing "ctx" parameter.

stark hearth
#

so

slate swan
#

ahhh

#

self,ctx

stark hearth
#

when using cogs, you need to add self as an argument in every command

dapper cobalt
rare saddle
#

Please tell me how to send a video or photo that is on a PC using a bot?

slate swan
#

Is this what your supposed to do if you want to delete a message after time?

    @commands.command(aliases=["purge","p","c"])
    async def clear(self,ctx, amount=5):
        await ctx.channel.purge(limit=amount+1)
        await ctx.send(f'Cleared {amount} messages!', delete_after=3)
brisk fiber
#

yeah

slate swan
#

ok, are the indentations right?

leaden anvil
leaden anvil
dapper cobalt
#

Also ctx.message.channel.send?

#

Why?? Just ctx.send.

dapper cobalt
#

Yes.

slate swan
#

how do i put command code in seperate files instead of one big file with all the commands

#

What is wrong with this?

    @commands.command(aliases=["purge","p","c"])
    async def clear(self,ctx, amount=5):
        await ctx.channel.purge(limit=amount+1)
        await ctx.send(f'Cleared {amount} messages!', delete_after=3)
await ctx.send(f'Cleared {amount} messages!', delete_after=3)
                                                             ^

IndentationError: unindent does not match any outer indentation level

slate swan
#

Just create a cog folder and put this in your main.py file

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')
final iron
#

Is there a function like TextChannel.history but for the entire servers history not just a specific channels?

crude crater
#

how would you type aliases for a command

final iron
#

Is it possible to search an entire servers message history?

maiden fable
final iron
final iron
slate swan
crude crater
#

ahhhh i was typing it wrong lol

final iron
crude crater
#

thank yall!

final iron
#
@bot.command(aliases=["aliases1", "aliases2"])
#

So back on my question is it possible to read an entire servers message history

#

Not just a specific channel

crude crater
#

oh then no

#

but in the top right hand corner you can do that

final iron
#

I'm talking about my bot

#

I'm not going to login with my bots token

crude crater
#

?

rare saddle
#

Can someone tell you how to send a file that is on your pc using a bot?

final iron
#

Not me

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
rare saddle
crude crater
#

So are you gonna use your bot or not?

final iron
#

I'm going to use my bot but im not going to login to its account

dapper cobalt
#

@final iron loop through the guild's text_channels and then through the history of each channel.

final iron
#

alr

#

Depending on how many channels there are that could be a bit slow right?

dapper cobalt
#

Yes.

hasty iron
#

you could create a task for each reading

slate swan
#

I thought it worked with files?

em.set_thumbnail(file = "logo.png")
em.set_thumbnail(file = "logo.png")

TypeError: set_thumbnail() got an unexpected keyword argument 'file'

hasty iron
#

with loop.create_task

#

but that could get you ratelimited

#

since they're going to be running concurrently

final iron
#

How would I iterate over channel.history

#

I'm getting an object is not iterable error right now

hasty iron
#

its a function that returns an async iterable

#

you have to call it first

final iron
#

Can I get an example of that please?

#

I'm not really sure what i'm supposed to do

hasty iron
#

you have to call channel.history

#

if you don't know how to do that, go back to python basics

slate swan
#

how do you get the guild the command was used in

dapper cobalt
night onyx
#

Please tell how would I get the time since when a person is boosting my server

final iron
hasty iron
#

!d discord.TextChannel.history

unkempt canyonBOT
#

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

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

Examples

Usage...
hasty iron
#

its pretty clear

final iron
#

Maybe to you its clear but for some people its not

night onyx
#

Hey what should I do if value field of embed.add_field has two possible values

round yarrow
#

My bot wont work and show "improper token passed"
I ENTERED TOKEN AND NOT CLIENT ID/SECRET
I DIDN'T ADD ANY SPACES OR ANYTHING IN MIDDLE OF THE TOKEN
I ALREADY TRIED REGENERATING THE TOKEN

final iron
hasty iron
celest cobalt
#

but it wont wait rn

full lily
#

From my experimentation, buttons seem to stop working after a certain time or the bot is restarted. Is there a way to make them permanent or restore their functionality after the bot is reset?

pliant gulch
#

There is an example of persistent views on the github page

full lily
#

I'll have a look 👍

celest cobalt
#

any1?

hasty iron
#

your code already does what you want

slate swan
#

Because that seems to dm everyone in the server which will likely rate limit the bot

#

I'm afraid I can't help

#

As you seem to write malicious code

swift raven
#

Hello everyone, don't you know by chance why he writes to me that there are mistakes that I did not do?

swift raven
full lily
#

hm i'm not really sure without seeing the whole thing. Perhaps you have it defined somewhere

swift raven
#

There is no

slate swan
#

Why are you getting the token from a config

full lily
#

you imported Embed I see

#

it should still be capital "E" though

dense thunder
#
from discord.ext import commands  # This is the part of discord.py that helps us build bots
import discord
#aye yo wtf is all these? lmao
bot = commands.Bot(command_prefix="!")
bot.run("yeetboii")
bot.load_extension("somecommands")


class someCommands(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command(name="ping")
    async def ping(self, ctx: commands.Context):
        """Get the bot's current websocket latency."""
        await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms")

    @commands.command(name="setstatus")
    async def setstatus(self, ctx: commands.Context, *, text: str):
        """Set the bot's status."""
        await self.bot.change_presence(activity=discord.Game(name=text))



def setup(bot: commands.Bot):
    bot.add_cog(someCommands(bot))
#

why am i getting an error saying " CommandNotFound: Command "setstatus" is not found"

final iron
final iron
#

The name will default to the function name

dense thunder
final iron
dense thunder
#

oh

final iron
#

That is what the command name with be

dense thunder
#

so if i just put in quotaitons

#

it doesnt need the name parameter?

final iron
#

Just remove the name parameter

dense thunder
#

ill keep it for now as im learning

final iron
#

alr

dense thunder
#

more readable

final iron
#

Not really

dense thunder
#

thank you i didnt know that though

#

nvm u right ill do it your way

final iron
#

Anyone know if you can use async for back to back in the same command

#

Because it wont for me

dense thunder
#

water, why am i getting the errror though?

final iron
final iron
#

Thats why its not working

vagrant brook
#

If you have your Cog in the same file as bot

#

Just call bot.add_cog(someCommands(bot))

#

Why bother doing def setup

maiden fable
#

Yea

vagrant brook
#

wdym back to back

final iron
#

Like just 2 different async for statements

winter vessel
#

any suggestions on what database library I should use for holding game data? like is sqlite3 good enough? or is there anything more tuned towards this (rpg game, stats based on member interactions in different channels)

maiden fable
#

Well it really depends. Go for either postgresql if u want an SQL db or Mongo if u want NoSQL db

hasty iron
#

if so, then yes you can nest as many functions as you want

final iron
#

No not nested

#

Basically the top statement will break the one below it

slate swan
#

what am i doing wrong?

hasty iron
winter vessel
#

@maiden fable thank you for your response

maiden fable
#

Oops, a typo. Fixed it

final iron
#
        async for msg in channel:
            if hard_n in msg.content:
                hard_n_counter += 1

        async for msg in channel:
            if soft_n in msg.content:
                soft_n_counter += 1
#

These are inside a command

hasty iron
#

that works

slate swan
hasty iron
#

but why dont you do it inside a single for loop

final iron
#

Idk

#

It doesn't work tho

hasty iron
#

what is channel

final iron
#

channel = ctx.channel.history(limit=100)

#

Lemme see if I can explain this better

hasty iron
#

ok so what do you mean by "it doesn’t work"

final iron
#

The 2nd for loop just doesn't work

#

It doesn't add on

#

To the counter

hasty iron
#

oh wait

#

i believe it consumes the messages

final iron
#

wdym

hasty iron
#

not sure

#

uh

#

removes them

#

cuz ur using a single instance of an async iterator

#

just do everything in a single for loop

final iron
#

Is that possible because they're looking for 2 different words

hasty iron
#

ok so why does that matter

final iron
#

Idk just wondering

hasty iron
#

try it

#

and see if it works

lofty mulch
#

Technically, could I call a class straight from the main file?

hasty iron
#

yes?

lofty mulch
#

Thanks, was in doubt about it

#

Wait, did you fully understand my question?

final iron
#

Yeah it works now

hasty iron
final iron
#

Can you explain more why it didn't work when I had 2 separate statements?

hasty iron
#

explain your question with a code example

lofty mulch
#

I started building the bot by the cog first

reef trail
#

what???

lofty mulch
#

Thing is, I'm too lazy now to declare it as a cog

#

So could I just slap the client.run and it's going to work normally?

hasty iron
#

what

#

i didnt understand anything

lusty swallow
#

i mean isn't declaring cog just add_cog()?

lofty mulch
#

Alright, I'll just rephrase it

reef trail
#

Why does this work instead?

lofty mulch
#

I didn't write the main file yet, I started writing the Cog.py file with the commands and stuff

#

Thing is, I want to test the commands real quick, but I'm kinda too lazy to declare the Cog.py as a Cog and also write the Main file itself

#

Could I just merge those both in the same file and it's going to work normally?

hasty iron
#

its literally like 6 lines of code

lusty swallow
#

well just execute setup function while passing a bot object

reef trail
lofty mulch
#

Welp, kay

#

Thanks

hasty iron
reef trail
reef trail
#

self = self.bot

lusty swallow
reef trail
#

wdym by that?

#

Like, ive only used cogs my entire time making a bot, i dont know what you mean

lusty swallow
#

like just open the cog file and it works as a bot by itself

reef trail
#

oh, loading it

#

OH

#

you can do that?

hasty iron
reef trail
#

and not hard coding the mention

hasty iron
#

use ClientUser.mentioned_in

#

oh you wants startswith

reef trail
#

yeah

lusty swallow
# reef trail you can do that?
if __name__ = '__main__':
    bot = #make bot
    setup(bot)
    bot.run(token)
```Just add this at the end and it should work too
hasty iron
#

why run setup? import the class and call bot.add_cog

lusty swallow
reef trail
#

its like less than 10 lines to load all your cogs when you launch your main file

#
for file in os.listdir("Cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        if name != "music":
            bot.load_extension(f"Cogs.{name}")```
 legit this is all you need (you can ignore the music part, its for my own stuff)
hasty iron
lusty swallow
hasty iron
#

so why not call it directly??

lusty swallow
hasty iron
#

call bot.add_cog directly

lusty swallow
#

yeah the code is pretty weird but i'm used to adding test_cases in my modules too not just discord cogs. It execs when it's ran directly

hasty iron
#

you use pytest or unitest?

lusty swallow
#

well no. Most modules i make doesn't return anything but instead does stuff like send files and it doesn't return anything

reef trail
#
@commands.Cog.listener(name="on_message")
async def SelfPingResponder(self, ctx):
    testing = self.bot.get_guild(755722576445046806)
    embed = discord.Embed(title="Why you ping me?", color=EMBED_COLOUR,
                          description=f"My default prefix is `tp!`.\nIf a custom prefix was set and you dont know it, you can use my mention as a prefix!\nNormally, AGB's nickname is set to contain its prefix and it will update when the prefix is changed. If the bot doesnt have permissions to update its nickname, this feature will obviously not work. If there is no nickname thats set currently, please report this to an Admin or to {ctx.guild.owner.mention}\nExample on how to use my mention as the prefix:{self.bot.user.mention} prefix")
    embed.set_thumbnail(url=ctx.author.avatar_url)
    if ctx.author.bot:
        return
    if ctx.message.content.startswith("@wind axle"):
        if ctx.guild.id == testing:     
            await ctx.channel.send(embed=embed)
        else:
            return
        
        
``` would this work blanket
hasty iron
#

try it

reef trail
#

i dont like errors, cluttered console = bad console

hasty iron
#

wait you’re comparing an int to a Guild object

reef trail
#

for testing purposes rn

#

dont want it to work globally until i know it works without issues

#

yknow

hasty iron
#

or clear it

reef trail
#

I mean, not with my host

#

Doesnt give me shell access

hasty iron
#

os.system("cls") lol

reef trail
#

oh

#

Huh. i guess i could do that

hasty iron
#

dont know if it will work as intended though

reef trail
#

it should

#

also

#

is the ! needed in the mention?

#

copilot suggested it

maiden fable
hasty iron
#

also how do you not have shell access

maiden fable
#

os.system()

reef trail
#

Because i dont

hasty iron
#

if its a vps

#

you should have shell access

maiden fable
#

U can instead use asyncio.create_shell_process or so idr

reef trail
#

its a Pterodactyl shell

hasty iron
#

if the operation takes some time

#

i dont think clearing the console would be a very blocking operation

maiden fable
#

Well for me it was, but ok

#

Idk could be my VPS

#

But I don't use it now

hasty iron
#

i mean you shouldn’t

#

but they apparently dont have shell access

reef trail
#

see what i mean @hasty iron

hasty iron
#

whats that type a command

reef trail
#

It doesnt actually execute a shell command

hasty iron
#

wtf

lusty swallow
#

f

reef trail
lusty swallow
#

try /help

hasty iron
#

ur mom

reef trail
#

yus

lofty mulch
#

You know

#

I actually didn't expect it to work on first try

reef trail
#

blanket

#

is the ! in the mention needed

hasty iron
#

i dont think so

reef trail
#
if ctx.message.content.startswith("@wind axle"):```
hasty iron
#

@hasty iron

#

try both i guess?

reef trail
#

Alright

#

wait i wonder

#

@wind axle

#

Huh, i think it works regardless

hasty iron
#

advertisement

lusty swallow
#

i don't think it worked lol

reef trail
#

Unintentional

#

nah it worked

hasty iron
#

it worked for me too

lusty swallow
#

wait is this expected lol

reef trail
#

no for people who have mutual servers with it it'll show the ping

lusty swallow
#

discord for windows is janky

#

ohh

#

k

reef trail
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/Cogs/info.py", line 426, in SelfPingResponder
    if ctx.message.content.startswith("@wind axle"):
AttributeError: 'Message' object has no attribute 'message'```
 @hasty iron i legit dont understand
hasty iron
#

your Message object is named ctx

reef trail
#

wouldnt that work?

hasty iron
#

Message.message doesn’t exist

reef trail
#

well using ctx.content doesnt work either, so just remove ctx?

lusty swallow
#

Get the ctx if you need it

hasty iron
#

no dont get it

reef trail
#

i have it in the.. typehint thing

hasty iron
#

you have a Message object

reef trail
#

(self, ctx) this part

hasty iron
#

typehint??

reef trail
#

idk what its called

hasty iron
#

ur inside an on_message event

lusty swallow
#

that's not a typehint

reef trail
#

this omg, idk what its called

hasty iron
#

function

lusty swallow
#

on_message returns message object not context

tulip oracle
#

what error do i need to except if the contents was too big for the embed

lusty swallow
tulip oracle
#

if its description it wont

#

if lets say it was more than the embed char cap

lusty swallow
#

try it actully i'm curious

#

and see what it raise

tulip oracle
#

ight nvm then, one sec

reef trail
#

sorry that i vanished my mom brought home sushi

lusty swallow
reef trail
#

yes

rare saddle
#

God, what's wrong with this damn codes, I got sick of fixing mistakes all day

tulip oracle
#

you are missing a positional argument, somewhere in cogs.voice lmao

lusty swallow
#

did you give it a source

tulip oracle
#

not a great traceback

rare saddle
#

The photo shows:

def __init__(self, source: YTDLSource):
        self.source = source
        self.requester = source.requester
rare saddle
tulip oracle
#

guess we know now

lusty swallow
rare saddle
#

I just don't understand what else he needs, there are always some mistakes

lusty swallow
plucky shoal
#

!ytdl

unkempt canyonBOT
#

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

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

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

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

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

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

See at this first screenshot at the very top

#

It's a bit cropped, but you can see the ytdl

brisk fiber
#

what's the best practice for storing a bot's token? my bot is a private bot only meant to be used on one server, and i'm hosting it on a raspberry pi. the code is in a public github repo. right now i have the token in a separate python file that's listed in my .gitignore and i import the token into my main bot file to run it– is this secure enough? should i use a .env file instead?

reef trail
#

if you're not posting your token to the repo you'll be fine

plucky shoal
#

thisYeah pretty much

wispy spade
brisk fiber
#

alright sounds good, thanks all!

graceful gulch
reef trail
#

btw @hasty iron should i just remove ctx? since ctx.content doesnt work would just message.content work?

#

or, should i have everything set as message?

rare saddle
reef trail
#
@commands.Cog.listener(name="on_message")
async def SelfPingResponder(self, message):
    embed = discord.Embed(title="Why you ping me?", color=EMBED_COLOUR,
                          description=f"My default prefix is `tp!`.\nIf a custom prefix was set and you dont know it, you can use my mention as a prefix!\nNormally, AGB's nickname is set to contain its prefix and it will update when the prefix is changed. If the bot doesnt have permissions to update its nickname, this feature will obviously not work. If there is no nickname thats set currently, please report this to an Admin or to the Owner of this server.\nExample on how to use my mention as the prefix: <@{self.bot.user.id}> prefix")
    if message.author.bot:
        return
    if message.content.startswith("@wind axle"):
        if message.guild.id == 755722576445046806:
            await message.channel.send(embed=embed)
            await message.channel.send("testing")```
 please someone explain to me why this isnt working, its not sending a single thing
edgy lion
#
                        now = datetime.datetime.utcnow()
                        delta = now - afkvar[3]``` the afkvar[3] is the datetime in this pic

```py
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\49176\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Elly - Test Version\cogs\afk.py", line 131, in on_message
    delta = now - afkvar[3]
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'```

https://cdn.discordapp.com/attachments/381965515721146390/886349188328202300/unknown.png
wicked atlas
wicked atlas
wicked atlas
#

!d datetime.datetime.strptime

unkempt canyonBOT
#

classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.

This is equivalent to:

```py
datetime(*(time.strptime(date_string, format)[0:6]))
```  [`ValueError`](https://docs.python.org/3.10/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3.10/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3.10/library/datetime.html#strftime-strptime-behavior).
hasty iron
#

you should store the timestamp instead

#

and you wouldn’t have to worry about precision

#

and formatting

bold dawn
#

I’m getting stuck on this error anyone knows why?

    async def help(self, ctx):
        """
        Displays a useful list of commands.
        """
        desc = ""
        for key in self.bot.commands.keys():
            command = self.bot.get_command(key)
            if command.hidden and not checks.is_owner(ctx):
                continue```
And I’m getting this error any idea why?  

 for key in self.bot.commands.keys():
AttributeError: 'set' object has no attribute 'keys'
hasty iron
#

Bot.commands is a set of Command

#

not a dict

#

!d set

unkempt canyonBOT
#
set

class set([iterable])``````py

class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3.10/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3.10/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.

Sets can be created by several means:

• Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`

• Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`

• Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
bold dawn
#

Ok thank you

reef shell
#

Any stable fork of dpy available yet?lemon_angrysad

#

Which support slash commands

hasty iron
#

make your own

#

you just have to add models and that’s it

bold dawn
wicked atlas
#

And it is a set of command objects. You don't need to fetch the command afterword

bold dawn
#

I’ve tried that

full lily
#

I can't figure out how to change a channel description. Can anyone advise?

kindred epoch
full lily
#

👍

reef shell
#
@commands.command()
async def blah(self, ctx):
				#cmd stuffs
@blah.error
async def blah_error(self, ctx, error):
			#error handler```
I use error handlers like this for every specific commands, now my question is if i  define a on_command_error event will it overwrite all these error handlers?
wicked atlas
#

It shouldn't

#

Is it the global bot.on_command_error event?

reef shell
#

Yes

wicked atlas
#

Then no, it shouldn't

reef shell
#

Ok I'll try that if it works this way

scarlet snow
#

!pypi aiosqlite

unkempt canyonBOT
crude crater
#

how would i write this for an addrole "You cannot add a role higher then your top role to yourself!"

#

member == [?]

#

what would i put there

#

!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
#
@client.command()
@commands.has_permissions(manage_messages = True)
async def addrole(ctx, role: discord.Role, member: discord.Member):
    guild = ctx.guild
    await member.add_roles(role)
    await ctx.send(f'I succesfully added role {role} to {member}')
###########################################################################################################################
    if member == guild.owner:
            return await ctx.send("You can't give roles to the server's owner!")

    if member.top_role > guild.me.top_role:
            return await ctx.send(f"This member's top role is higher than yours!\n\n{member.top_role.name} <-- {member.mention}'s top role\n\n{ctx.author.top_role.name} <-- Your top role")

    if member.top_role > ctx.author.top_role or member.top_role == ctx.author.top_role:
            return await ctx.send("You cannot give roles to someone with a higher or equal role to you!")

    if member.top_role == guild.me.top_role:
            return await ctx.send("This member's top role is equal to your top role!")

    if member == ctx.author:
            return await ctx.send("You cannot add a role higher then your top role to yourself!")
#

would it be

    if member == ctx.author.top_role:
tame nymph
#

UPDATE subscriptions SET nitro = true WHERE userId = 763854419484999722

crude crater
#

or maybe

    if role == ctx.author.top_role:
#

?

agile goblet
#

role has a position attribute

crude crater
#

what dat mean

open forge
#

Alright, I have some objects as follows:

class CustomGuild(Guild):      
    def __init__(self, instance):
        self._instance = instance

    def __getattr__(self, name):
        return getattr(self._instance, name, None)

class CustomContext(commands.Context):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cguild = CustomGuild(self.guild)

I try to implement it like such:

context = await self.client.get_context(message, cls=CustomContext)
await self.client.invoke(context)

But I've got a weird problem, to say the least.

In my commands, the Context object gets passed as CustomContext, but when I try to access the cguild attribute, an attribute error is raised saying that the Context object doesn't have that, but ctx shouldn't be a Context object, and if I print the type, it's labeled as a CustomContext.

Despite an AttributeError saying there is no attribute called cguild, cguild is still actually an object, and I can call the methods and attributes from it. I'm not sure what I'm doing wrong here, why is an error being raised despite the code (seemingly) working?

pliant gulch
#

Does this mean you are seeing a type error on your IDE or does it actually raise the error

open forge
#

On mobile, one second,

And it's actually raising an error.

vale root
#

How do i make a embed have a click able link

slate swan
#

just put a link in the embed it should work

vale root
#

It dose not

#

it shows the link as text

#

wait nvm

slate swan
#

how to fix this eror

vale root
#

With my embed how do I set the size of the thumbnail?

#

Right now its small as hell

vale root
slate swan
#

alr 1 sec

unkempt canyonBOT
slate swan
#

this is code

visual island
slate swan
#

it worked

#

thanks

#

i get this but thats not the mesage i wanted to be

#

i did $help which is ment to print

#

{Fore.BLACK}|| hells Corp discord bot
{Fore.BLACK}|| made by el pacho
{Fore.BLACK}|| published by el pacho
{Fore.BLACK}||this is el pachos slave
{Fore.BLACK}||current commands are:
{Fore.BLACK}||$help
{Fore.BLACK}||$cum
{Fore.BLACK}||$nitro
{Fore.BLACK}||$discord
{Fore.BLACK}||$mod

#
-----------------------------------------
{Fore.BLACK}|| hells Corp discord bot
{Fore.BLACK}|| made by el pacho
{Fore.BLACK}|| published by el pacho
{Fore.BLACK}||this is el pachos slave
{Fore.BLACK}||current commands are:
{Fore.BLACK}||$help
{Fore.BLACK}||$cum
{Fore.BLACK}||$nitro
{Fore.BLACK}||$discord
{Fore.BLACK}||$mod
-----------------------------------------```
#

its ment to print this

#

but instead of the Faore.black its ment to show smt else

#

anyone know a fix

vale root
#

When I run this

@commands.Cog.listener()
    async def on_member_join(self, member: discord.Member):
        channel = self.bot.get_channel(884131769673203772)
        print("Member join: {member}")
        if not channel:
            return 


        await channel.send(f"Welcome, {member} be sure the read our rules!")

Nothing happens i dont event get a print in terminal

#

Why is it not workin

slate swan
#

did you enable intents?

vale root
#

mhm

#

wait hang on

#

Yep still dose not work

#

I have member intent and intent

#

It has admin perms

#

And its not workin

slate swan
#

maybe try this? ```py
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(884131769673203772)
print("Member join: {member}")
if not channel:
return

    await channel.send(f"Welcome, {member} be sure the read our rules!")
vale root
#

Thats the same?

#

wait

#

is it cus my return comes before the await channel.send?

junior falcon
vale root
#

hm

slate swan
#

but it doesnt hurt to try

stark hearth
#

!code

slate swan
junior falcon
#

oh sorry

stark hearth
#

how do you test like quick code with the python bot again?

arctic wadi
#

Hey guys catJAM

I'm working on a bot for my Axie Infinity scholars and I'd like to post messages in a channel, but in alphabetical order based off of their names
I created the class Scholar and have the scholar objects below. I'd like a function to sort by their name parameter and then run the functions to post message updates:

class Scholar:
  def __init__(self, name, API, ronin, discordID, embedColor, manager, scholarNumber, joinDate):
    self.name = name
    self.API = API
    self.ronin = ronin
    self.discordID = discordID
    self.embedColor = embedColor
    self.manager = manager
    self.scholarNumber = scholarNumber
    self.joinDate = joinDate
  def getDataSendMessages():
    print(test)

#Example Scholar Object
mattScholar_1 = Scholar("Camilla", "https://apiTest=000000000000000000000",
"ronin:000000000000000000000",
11111111111111111,
0x7289da,
"Matt",
"1",
"August 10th, 2021")

#Function Example
@tasks.loop(minutes = 60)
async def sendScholarMessages():

  testBotChannel = client.get_channel(796021873733009449)
  #THESE below are what I'd like to get sorted based on the scholar's names :)
  await mattScholar_1.getDataSendMessages()
  await mattScholar_2.getDataSendMessages()
  await mattScholar_3.getDataSendMessages()
stark hearth
#

!e

n = 10
while n > 0 :
    print(n)
    n = n – 1
print('Blastoff!')
print(n)
vale root
#

!e


 @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(884131769673203772)
        print("Member join: {member}")
        if not channel:
            return 


        await channel.send(f"Welcome, {member} be sure the read our rules!")
unkempt canyonBOT
#

@vale root :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     async def on_member_join(self, member):
003 | IndentationError: unexpected indent
stark hearth
vale root
#

ok

#

I still cant find why the event is not working

slate swan
#

i think its cuz of your @commands.Cog.listener() not indented

vale root
#

Nope

lusty swallow
#

it's probably because @commands.Cog.listener() is not indented

slate swan
#

basically what i just said

lusty swallow
#

check the line before than then

slate swan
#

How can Iget the total number of commands

lusty swallow
#

maybe

#

not sure

tame nymph
#

git rm -rf /
gives you free verified bot

hardy yoke
open forge
drifting arrow
#

How would I get a list of every member in the discord?

#

I want to create an anti-raid bot since my discords are getting raided a lot even with maximum security on discord. So I figured if I could just type a command like !raid and ban anybody who has recently joined and has a new account it'd be easier than manually removing them.

And one of the things I'd need is a list of every member in the discord. So how would I do that?

vagrant brook
#

!d discord.Guild.members

unkempt canyonBOT
drifting arrow
slate swan
#

Need help!
This is my code but i get this error:
**line 10 async def join(self,ctx)
^

@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voicec hannel")
voice_channel = ctx.author.voice.channel
if ctx.voice_channel is None:
await voice_channel.connect()
else:
await ctx.voice.channel.move_to(voice_channel)

vagrant brook
#

Are you using python 3

slate swan
#

ERROR
line 10 async def join(self,ctx)
^
IdentationError: Unexpected indent

vagrant brook
#

Why is there a random space for no reason whatsoever 🙂

slate swan
#

ohhh

#

well hehehe

drifting arrow
#

@slate swan your code isn't properly indented if that's your actual code 🤔

slate swan
#

but now its error in line 20,wait i will send @vagrant brook

slate swan
#

@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()

vagrant brook
#

Same error

#

🙂

drifting arrow
#
@commands.command()
async def join(self,ctx):
    if ctx.author.voice is None:
        await ctx.send("You are not in a voicec hannel")
        voice_channel = ctx.author.voice.channel
    if ctx.voice_channel is None:
        await voice_channel.connect()
    else:
        await ctx.voice.channel.move_to(voice_channel)
slate swan
#

tnx

drifting arrow
#

fixed indentations in first code.

vagrant brook
#

He's using 2 spaces indentation

drifting arrow
#

there's a special place in hell for 2 space indentations

slate swan
#

bruh

#

now we got more errors ):

#

def setup(client):
client.add_cog(music(client))

#

last line

#

it says its a error but we can't indentify where

drifting arrow
#

I don't deal with the music/voice part so I wouldn't know

#

What's the error exactly?

slate swan
#

BRH

#

I FKN DELETED MY CODE

vagrant brook
#

Press ctrl +z

slate swan
#

OMG TNX

#

<33

drifting arrow
#

Ctrl+z = undo.
Ctrl+y = redo

#

at any rate @slate swan, fix your indentations..

def setup(client):
    client.add_cog(music(client))
slate swan
#

well back to the error

vagrant brook
#

What's the error anyway

#

indentation seems fine

slate swan
drifting arrow
#

Is your class using the commands.Cog?

#
class Example(commands.Cog):
```?
pliant gulch
# slate swan

discord.Client does not have cogs, you need commands.Bot

maiden fable
unkempt canyonBOT
#

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

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

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

Use this, not discord.Client, yea

slate swan
#

soo,what should i do?

pliant gulch
slate swan
#

i dont understand really

drifting arrow
maiden fable
#

.......

slate swan
#

wtf

pliant gulch
# slate swan soo,what should i do?

Currently your client is defined as discord.Client you want to switch that to commands.Bot, this is a class that inherits discord.Client so a few things are different. Your gonna want to check out a guide

maiden fable
slate swan
#

but i dont have discord.client anywhere in my script...

slate swan
vagrant brook
#

Yes

vagrant brook
maiden fable
#

Yea

slate swan
#

okey,I switch it

#

hope it will work now,i want sleep 💤

maiden fable
#

Haha I know that feeling

slate swan
#

next error....

#

client = commands.Bot()
this is line 6

final iron
#

Are there any legitimate ways to create a music playing bot?

signal forge
maiden fable
signal forge
#

whether through your config file or manual

maiden fable
#

command_prefix="#" Or something

signal forge
#

for example I have:

bot = commands.Bot(
        conf.get("prefix", "!"),
        activity=discord.Activity(
            name="Leothelion", type=discord.ActivityType.streaming
        ),
    )
maiden fable
#

Or u can do just "#"

maiden fable
signal forge
#

i'd love to send a link to the documentation but apparently that is against code of conduct

#

so i'm going to just give examples

slate swan
maiden fable
slate swan
#

witch line should the prefix be?

maiden fable
slate swan
#

):

maiden fable
#

In the Bot("#")

signal forge
#

also naming commands.Bot as Client is going to be awfully confusing

slate swan
#

i give up

maiden fable
#

Hey @slate swan, I prefer u go to the website I posted above and look into that tutorial. That will help you get an understanding of the basics of the dpy library

slate swan
slate swan
#

but anyways

#

no errors now

#

so i think it will work'

maiden fable
#

Well nope

#

You ain't loading the cogs properly

slate swan
slate swan
sudden magnet
#

is there a reason this doesn't work or does close just not work with cogs? python @commands.Cog.listener() async def close(self) -> None: print(f"[EXIT ] Shutting down...") self.bot.save() await self.bot.close()

boreal ravine
slate swan
#

idk,im new,im programming this bot with my best friend

boreal ravine
slate swan
#

remove the one in line 6 and move the one in line 17 to line 6

slate swan
boreal ravine
slate swan
#

i think hes new to coding

slate swan
boreal ravine
#

@slate swan Also make the "Client" lowercase :)

slate swan
#

yes

boreal ravine
#

if ur new to dpy just make the commands all in one folder lol

maiden fable
#

Also, why not instead loop over the list elements instead of range?

slate swan
#

i dont understand

#

):

#

i will go to sleep,bye.

maiden fable
#

U r doing range(len(cogs))
But why not do cogs

signal forge
#

helps to read the documentation that describes and lists all the available args

#

but i can't link it

#

against CoC

maiden fable
#

This all can be a bit too much since u r just a beginner, so I seriously suggest you to look into some OOP and checkout that tutorial I have sent twice

boreal ravine
#

mhm object orienting programming

pliant gulch
maiden fable
unkempt canyonBOT
#

class discord.ext.commands.Cog```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
maiden fable
signal forge
pliant gulch
#

!e ```py
cogs = [1]

for i in range(cogs):
print(i)

unkempt canyonBOT
#

@pliant gulch :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: 'list' object cannot be interpreted as an integer
maiden fable
#

I mean

signal forge
#

i'm not going to argue with the moderators

maiden fable
#

Removing the range also and looping over the elements

maiden fable
signal forge
#

that's what I thought i was doing, but obviously we have no power to make that call

#

anyway

maiden fable
#

Yea nvm

signal forge
#

if you don't have many cogs to add, you can just

bot = commands.Bot(<args>)
bot.add_cog(<cog name and params>)
#

in your case bot would be client

maiden fable
#

Yea

#

Wait no

#

!d discord.ext.commands.Bot.load_extension this is used for loading the cogs

unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
signal forge
#

oh? i use add_cog

slate swan
#

yeah

#

bot.add_cog is for adding it not loading it

maiden fable
signal forge
#

that is good to know

signal forge
#

i presumed cogs are loaded at the stage when you do bot.run("token")

#

thanks for the info

slate swan
#

Eh

#

I seriously hate programming

signal forge
#

the same way you'd hate riding a car without knowing how to change gears

maiden fable
#

Indeed

slate swan
#

But it’s funny to create something creative

maiden fable
#

Well Volle. What you are doing is, tryna drive a car when you don't know how to drive it. That's the same thing that's happening to you.
I prefer you learn the basics first and then go for Cogs as this is an advanced part of the library.
I have linked that tutorial which will make u understand OOP and the basics of the library, then you can go for Cogs (that tutorial also tells how to use Cogs BTW)

slate swan
#

Mhm true

#

Yeah I saw that,

#

I started reading it,but I’m so tired right now so I have to go.

maiden fable
#

Well that's okay. Have a good night!

slate swan
#

Godnight

round quarry
#

How can I add to the commands that certain permissions are required?

maiden fable
unkempt canyonBOT
#

discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
maiden fable
#

This?

slate swan
#

or you could check if the person has a specific permission in the command

hollow agate
#
@client.command()
async def userinfo(ctx, member: discord.Member = None):
        target = member

        embed = discord.Embed(
            title=f"User Information",
            color=0x00a8ff,
            timestamp=datetime.utcnow())

        embed.set_thumbnail(url=member.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)``` How can I make this check if the user is none/if the user isn't none?
round quarry
# maiden fable This?

It's that, but how do I make the bot say something like, "You don't have permissions to run the command. Missing permissions: Manage messages.

signal forge
hollow agate
#

Thank you!

vapid berry
#

!discord discord.MessageEmbed

fleet oracle
#

How can I divide these files into folders inside the cogs folder and still have the bot keep taking those files?

signal forge
#

add an __init__.py

#

in the folder

vapid berry
#

how can i make embed message?

signal forge
#

for example i have a folder called modules that contain multiple cogs, one of which is called webscraping and inside it there is a file called arxiv.py where the class Arxivfetch exists. With this sort of structure, you just need to do:

from modules.webscraping.arxiv import Arxivfetch

in the main file

#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

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

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

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

🤔

signal forge
#

you use the discord.Embed class to create an embed

#

and you can add fields by using add_field

#

there's also things like set_thumbnail, set_footer, set_image etc

fleet oracle
#

excuse me

signal forge
#

point is if you want to use folders, you need to have __init__.py in them

#

so that they are treated as packages

fleet oracle
#

and what should go inside that file?

signal forge
#

you can leave it empty

fleet oracle
#

oh

fleet oracle
signal forge
#

well that depends on how your directories are set up

somber musk
#

So
Don't judge me
But how do I code a bot that chooses a random person that reacted a certain reaction to the bots command?
(I use replit, just bc it has 24/7)

lofty mulch
#

ModuleNotFoundError: No module named 'Dryfile'

What exactly is this error? I'm trying to declare a cog

#

I've tried pip updating, but it's still weird

#

DryFile is just a name, don't worry

signal forge
#

is dryfile in another directory?

lofty mulch
#

It's on the cogs folder, but I've listed it

#
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')```
signal forge
#

that just gives the names of the file doesn't it

#

not the class name

maiden fable
lofty mulch
#

OooO

#

Actually, nevermind

#

My class is also named Dryfile

#

What if I change it?

signal forge
#

yeah but if you have a class named Dryfile in dryfile.py then you shuold be importing like

from dryfile import Dryfile
hollow agate
#

Is there a place where I can see the list of all the datetime timezones?

hollow agate
#

Kinda, py timestamp=datetime.utcnow()) I just wanna change this timestamp to my timezone (Mountain Standard Time)

lofty mulch
#

I remember reading about this on the import time documentation, lemme see if I can retrieve it

signal forge
#

!pypi tzlocal

unkempt canyonBOT
signal forge
#

would something like this be useful

#

?

opal magnet
#

You just want a list of timezones like this?

signal forge
#
I just wanna change this timestamp to my timezone (Mountain Standard Time)
#

i thought this was the primary intention

hollow agate
# signal forge

Vs code doesn't seem to register these imports for some reason

hollow agate
signal forge
#

have you installed tzlocal through your python package manager?

hollow agate
#

No, how do I do that? 😂

signal forge
#

depends, are you using conda or pip?

hollow agate
#

pip

signal forge
#

then do pip install tzlocal

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 60003): Two factor is required for this operation

#

how do i fix this

opal magnet
#

So, I was messing aroung with regex (probably in the wrong way) trying to make something similar to Rollem dice system. It was working until I noticed it wasn't. Basically whenever I run any number of dices diferent than 1 (Ex: 3d20) it will run the command twice.

My command:

    @commands.command()
    async def r(self, ctx: commands.context.Context, roll):

        dice_pattern = r'(\d+|)d(\d+)(\+\+\d+|\-\-\d+|\d+|[\+\-]\d+|)'
        if re.match(dice_pattern, roll):
            vals_list = []
            modif_list = []

            sep = re.search(dice_pattern, roll)
            times = int(sep.group(1)) if sep.group(1) != '' else 1
            value = int(sep.group(2))
            modif = sep.group(3) or 0; mod = f'{modif[0]} {modif[1:]}' if modif != 0 else ''

            if times >= 100 or value >= 100000:
                await ctx.reply('A quantidade de dados não deve passar de 100000.')
                return

            for i in range(times):
                gen = randint(1, value)
                vals_list.append(gen)
                modif_list.append(f'{gen}+{modif}')

            if re.match(r'(\d+|)d(\d+)([\+\-]\d+|)', roll):
                result = eval(f'{sum(vals_list)}+{modif}')
            else:
                result = eval("+".join(modif_list))

            print(modif_list); print(vals_list); print(result)


            await ctx.reply(f'{result}{sorted(vals_list, reverse=True)} {times}d{value} {mod}')
hollow agate
#

Ahh, ty

signal forge
#

have you tried debugging with print statements?

brazen raft
#

Maybe replace message.channel.purge(limit=1) with message.delete()

#

Then it's a permission problem?

boreal ravine
#

Can embed.set_author not be in order like embed.set_author(icon_url=..., text=... like this?

brazen raft
#

Oh my god sorry

boreal ravine
#

Read what you sent

brazen raft
#

Put it in like <@>

#

After the @

lofty mulch
#

Also, I've heard that Discord.py won't be updated in a while

#

Is this true?

signal forge
#

in a while is an understatement

lofty mulch
#

It will be gone, then?

brazen raft
#

For example, to mention me using code you'd have to send @brazen raft

lofty mulch
#

That's quite sad, actually

brazen raft
brazen raft
#

He wants to mention himself

boreal ravine
#

yes

#

use the ID then

brazen raft
#

Wait @hollow iron what's e

signal forge
#

e = message.author

boreal ravine
#

e = message.author

signal forge
#

<@672580539513045013> certainly works

brazen raft
#

message.author.mention

signal forge
#

i thought they wanted the bot to ping the owner (assuming it's them) and not the author

boreal ravine
#

His

await message.channel.send('<' + '@Vaprant#7777' + '>' + ' Bruh, did ' + e + ' really just try that?, don' + "'" + 't worry, hes banned lol!')

Mine

await message.channel.send(f"@hollow iron Bruh, did {e} really just try that? Don't worry, he's banned lol!")
``` why not make it like this
signal forge
#
how do i get it to ping me and say the author in ...
#

right

#

ping both you and the author

signal forge
#

yeah the lack of f-strings really makes it hard to read the code

boreal ravine
#

Formatting strings

brazen raft
#

!f-string

unkempt canyonBOT
#

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

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

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

signal forge
#

i mean it's not wrong either but it's just hard to read

boreal ravine
#

both works

lofty mulch
#

And now I got a different error

#

I got something right, atleast

#
TypeError: 'module' object is not callable```

What exactly is this?
lofty mulch
#

oops

boreal ravine
#

You can use " " or ' '

signal forge
#

this is why f-strings are superior

#

once u go f-strings u never go back

lofty mulch
#

I genuinely don't know if I should laugh or cry

boreal ravine
#

Some people have an f string addiction 😔

lofty mulch
#

It's like whenever I tap an error, another appears

#
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.DryFile' raised an error: TypeError: cogs must derive from Cog```
#

How can I fix this?

elfin island
#

Show your code

lofty mulch
#

Cog or Main?

signal forge
#

there is no class called Cogs

elfin island
#

Basically, your cog class should inherit from commands.Cog

slate swan
lofty mulch
#

Then I should replace my classes with Commands.Cog, got it

boreal ravine
#

Use message.author.name

signal forge
#

they said they wanted to ping the author as well

slate swan
#

try? ```py
await message.channel.send(f"@hollow iron Bruh, did {message.author} really just try that? Don't worry, he's banned lol!")

boreal ravine
#
<@{message.author.id}>
slate swan
#

hes trying to mention him self not the author

boreal ravine
#

wut

boreal ravine
#

hes tryna mention the guy that triggered the filter

drifting arrow
#

Can someone check this code and see if I've made any fatal mistakes? For example it won't work as I think it would?

@client.command()
async def raid(ctx):
    memberslist = []
    for i in client.guilds:
        for member in i.members:
            joineddate = datetime.now() - member.joined_at
            createddate = datetime.now() - member.created_at
            if joineddate.days <= 1 or createddate.days <= 1:
                mymembers = {
                    'Member name:': member,
                    'Member id:': member.id,
                    'Member roles:': member.roles,
                    'Created:': member.created_at,
                    'Joined:': member.joined_at
                    }
                memberslist.append(mymembers)
                member.kick('Kicked due to anti-raid procedures. If you believe this is in error, please contact our staff. <List of staff>')
                #await member.send('You have just been kicked due to our anti-raid procedures. \n If you believe this is in error, please contact our staff. <List of staff>')

    memberslist_string = '``` **Kicking these members:**\n\n'
    for i in memberslist:
        for a,b in i.items():
            memberslist_string += (f'{a} : {b} \n')
        memberslist_string += ('\n')
     
    memberslist_string += '```'
    await ctx.send(memberslist_string)

At the moment I dont have any test subjects so I can't exactly determine if it will work.

slate swan
#

@hollow iron

#

@hollow iron

#

same person

glacial echo
#

how can i make a command that enables an on_message(message) function 60 seconds after the command gets sent? i need to have a few commands that start various games, and when a game is started, 60 seconds later it needs to start the on_message(message) function for that game only, then after the game is complete or after 5 minutes of inactivity it should stop the function and allow commands again

drifting arrow
#

Wouldn't you use a separate command sheet for each game?

#

load them up. so you might do $load Quizzer

#

Also only allow your bot to handle 1 game at a time.

glacial echo
#

well thats basically what i want?

#

i want it to, in that channel or server (either or), only allow one game at a time to be started

#

but i dont want users to need to type a command for every single game

#

am i best to make like a state machine of some kind that updates to the "id" of the game and make a thing that only allows command to be processed in non-active channels?

#

and only processes non-command messages in their respective channel?

slate swan
#

how do I make a bot print when a command is used

glacial echo
slate swan
#

print

glacial echo
#

either way, your question makes it seem like you dont understand teh basics

slate swan
#

so like it would say the command ... was just run

slate swan
#

and some more advanced stuff to

#

to send it would be ctx.send

glacial echo
#
@client.command()
async def test(ctx):
  print("test complete")
#

this would print

signal forge
#

to the terminal yes

glacial echo
#
@client.command()
async def test(ctx):
  await ctx.send("test complete")
#

this will send a message

signal forge
glacial echo
#

but again, this is like the basics of a discord bot

slate swan
#

when any command is run not just printing is there not an event

glacial echo
#

any command?

slate swan
#

yes

high flame
#

hi, any idea how i get this:
https://retarded-people.online/​​ ‌‌‌(first screenshot underneath code)​​‌​​‌‌​​‌‌​‌‌‌​​​​​‌​‌​‌​​​‌​​​​​‌​‌‌​‌​​​​​‌‌‌​​‌​‌​‌​‌​‌
to this:
https://retarded-people.online/​ ‌(second screenshot)​‌​​​​​‌‌​​‌​​​​‌‌​​​‌​‌​​​​​‌​‌​​​​‌​​‌‌‌‌​‌​​​‌‌​‌‌​​‌​​‌‌​​

This is the code:

    @commands.command()
    async def userinfo(self, ctx, member: discord.Member = None):
        member = ctx.author if member is None else member
        roles_string = ', '.join([r.mention for r in reversed(member.roles[1:])])
        permissions_string = ', '.join([str(p[0]).replace("_", " ").title() for p in member.guild_permissions if p[1]])

        e = discord.Embed(
            colour=0xFCA41C,
            title=member
        )
        e.set_thumbnail(url=member.avatar_url)
        e.add_field(name=f'Joined at', value=member.joined_at.__format__('%A, %d %B %Y @ %I:%M:%S %p '))
        e.add_field(name=f'Registered at', value=member.created_at.__format__('%A, %d %B %Y @ %I:%M:%S %p '),
                    inline=False)
        e.add_field(name=f'Roles [{len(member.roles[1:])}]', value=roles_string, inline=False)
        e.add_field(name=f'Key Permissions', value=permissions_string, inline=False)
        e.set_footer(text=f'ID: {member.id}')
        await ctx.send(embed=e)
high flame
#

I want to make it so the first key permissions is the same as the second one, as in screenhots

slate swan
#

image link

high flame
#

LOL sorry, upload.systems link

#

cba to change it

slate swan
#

but could someone answer the question

glacial echo
#

try this?

slate swan
#

I found an event in the docs that fits my needs thank you though

glacial echo
#

np

high flame
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
#
if member == guild.owner:
            return await ctx.send("I cannot ban the server's owner!")
                
    if member == ctx.author:
            return await ctx.send("You cannot ban yourself!")

    if member.top_role > guild.me.top_role:
            return await ctx.send(f"This member's top role is higher than yours!\n\n{member.top_role.name} <-- {member.mention}'s top role\n\n{ctx.author.top_role.name} <-- Your top role")

    if member.top_role == guild.me.top_role:
            return await ctx.send("This member's top role is equal to your top role!")
#

how do i write more then one "if"?

#

like if one of them doesnt work then to try the next one? if that makes sense lmfaoo

glacial echo
crude crater
#

ok

glacial echo
#

so its

if thing == thing:
  stuff
elif thing == thing2:
  stuff
else:
  exception code stuff
lofty mulch
#

Also,

#

I've noticed that my Main file doesn't notify my terminal that the bot is online, even though i'm printing it

crude crater
#

for an "addrole" script how would i write something for if the role was too high to be given?

lofty mulch
#

Welp, too much

#

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

lofty mulch
#

I'm going to sleep now, so I'd appreciate if you could ping me with the answer so I can search for it later

glacial echo
#

if roleIndicated >= bot.top_role:
do code stuff here

high flame
#

hi, any idea how i get this:
https://retarded-people.online/​​ ‌‌
(first screenshot underneath code)​​‌​​‌‌​​‌‌​‌‌‌​​​​​‌​‌​‌​​​‌​​​​​‌​‌‌​‌​​​​​‌‌‌​​‌​‌​‌​‌​‌
to this:
https://retarded-people.online/​
(second screenshot)​‌​​​​​‌‌​​‌​​​​‌‌​​​‌​‌​​​​​‌​‌​​​​‌​​‌‌‌‌​‌​​​‌‌​‌‌​​‌​​‌‌​​

This is the code:

    @commands.command()
    async def userinfo(self, ctx, member: discord.Member = None):
        member = ctx.author if member is None else member
        roles_string = ', '.join([r.mention for r in reversed(member.roles[1:])])
        permissions_string = ', '.join([str(p[0]).replace("_", " ").title() for p in member.guild_permissions if p[1]])

        e = discord.Embed(
            colour=0xFCA41C,
            title=member
        )
        e.set_thumbnail(url=member.avatar_url)
        e.add_field(name=f'Joined at', value=member.joined_at.__format__('%A, %d %B %Y @ %I:%M:%S %p '))
        e.add_field(name=f'Registered at', value=member.created_at.__format__('%A, %d %B %Y @ %I:%M:%S %p '),
                    inline=False)
        e.add_field(name=f'Roles [{len(member.roles[1:])}]', value=roles_string, inline=False)
        e.add_field(name=f'Key Permissions', value=permissions_string, inline=False)
        e.set_footer(text=f'ID: {member.id}')
        await ctx.send(embed=e)
slate swan
#

How to make so a member can't type in a channel? Like how to change the channel permissions?

slate swan
#

Yeah

#

But how

crude crater
#

make a role

#

and then a command

slate swan
#

Like channel.edit(permissions=...)

crude crater
#

no in the discord

slate swan
#

Ik

#

But how to make the bot do it

#

Edit the permissions

unkempt canyonBOT
#

Hey @crude crater!

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

crude crater
#

omg

crude crater
slate swan
#

Yes

#

I need to have it automated...

ornate linden
#

quick question im too lazy to test

#

if a role has manage_roles perm can it remove administrator from a role below it?

crude crater
#

no

ornate linden
#

so only roles with administrator can change other role's permission to have administrator

#

?

crude crater
#

yes

ornate linden
#

ok

crude crater
#

does someone have a banned/blacklisted words script?

boreal ravine
#

script?

slate swan
#

How to use permissionoverwrite?

crude crater
boreal ravine
#

whats a script

crude crater
#

for a discord bot?

crude crater
boreal ravine
#

u mean free code

crude crater
#

huh?

slate swan
#

Dont giveaway code.

crude crater
#

why lmfaoo

#

i do it all the time

#

its honestly not that big of a deal lol

slate swan
#

🤦‍♂️

boreal ravine
slate swan
#

It is

crude crater
#

why would it be?

boreal ravine
#

it is infact a big deal

crude crater
#

why lol

#

its literally not, we have starving kids in liberia and nuclear war you think someone getting free code is a big deal?

boreal ravine
#

mhm

crude crater
#

crazy lmaoo

boreal ravine
#

ikr

crude crater
#

its such a minute thing, average life expectancy is 85 years and you're gonna get hung up on numbers and letters? it really ISNT that big of a deal

#

<3

boreal ravine
#

it is babe <3

fickle turret
#

i thought i was in some other channel for a second

crude crater
boreal ravine
#

it is :D

crude crater
#

elaborate

boreal ravine
#

elaborate what

#

theres nothing to elaborate

crude crater
#

why is it a big deal?

crude crater
#

because i asked for a script and they made an ordeal about it lol

cyan nest
#

Because it is a big deal

#

It's like asking for free lunch

crude crater
#

i really dont see how lmao

cyan nest
#

It's like asking for free lunch

crude crater
#

its not

cyan nest
#

It is

crude crater
#

its like asking for free code

drifting arrow
#

I just arrived. How big is this code he's asking for @cyan nest ? 🤔

slate swan
#

Rule 7. @crude crater

drifting arrow
crude crater
#

why make it seem like its like im asking for an entire bot or something lol

#

its a simple command lmao

cyan nest
#

Why don't you code it yourself

boreal ravine
#

^

slate swan
#

Exactly

drifting arrow
#

What are this discords rules on advertising your own job services? Coz I'd make it for him for a fiverr 😉

cyan nest
#

Turns out, these commands do take time to make

cyan nest
#

And most spend hours on building them

#

And you come and ask to them simply hand it over

crude crater
drifting arrow
crude crater
cyan nest
#

Then sleep, recover and code it yourself

crude crater
#

bro why are yall so AR lmao

boreal ravine
#

whats AR

cyan nest
#

How would you feel if you spent hours on building something nice

crude crater
#

cant say in here lol

cyan nest
#

And somebody just says "hand it over"

crude crater
cyan nest
#

Nice, we don't

boreal ravine
#

thats spoonfeeding

cyan nest
#

Good luck on your search

drifting arrow
crude crater
#

because they're gonna get good use out of it and its a simple thing just to do

cyan nest
#

If it's a simple thing

crude crater
#

and not doing it gets nothing done for nobody

cyan nest
#

Why don't you do it yourself

crude crater
#

i mean its a simple thing just to give it over lol

boreal ravine
#

very simple really just use on message event

cyan nest
#

Stop saying it's simple when it's not lol

crude crater
#

it really is

cyan nest
#

Then why are you asking

#

Make it yourself

#

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

cyan nest
#

You can do it, I believe in you

crude crater
#

what did you think i was gonna do if yall said no lmao

cyan nest
#

It's just a simple command

cyan nest
glacial echo
#

if someone has knowledge of a publicly available resource that contains common swearwords and/or knows of a library that provides them in some way, that would suffice? or does that break a rule?

crude crater
#

can yall like just let it go?

cyan nest
#

No one is giving your shit or anything, we're just talking

#

You shit*

glacial echo
#

nah your giving him shit

crude crater
#

its not a channel for "just talking" its for help

glacial echo
#

noone wants to research and write out like 100+ possible swear words or slurs

crude crater
#

and when i asked for help i got a lecture

cyan nest
#

Help ≠ Ask for free code

glacial echo
#

if theres a premade list taht already exists publicly whats the problem in linking it, or if someone already made one they were willing to share whats the issue there?

crude crater
# boreal ravine whats AR

A term used to refer to a person who feels a need to be in control of all aspects of his or her surroundings. Or, in other words, an anal retentive person "can't let go of shit."

#

AR= anal retentive

#

because you asked so nicely

boreal ravine
#

o ok

crude crater
#

because instead of a "no" i got a "iTs sUcH a bIg dEaL"

cyan nest
#

We literally told you no but you literally started saying that it's a big deal or whatnot

crude crater