#discord-bots

1 messages · Page 465 of 1

boreal ravine
#

But I said "no" nicely? You were supposed to stop there :/

cyan nest
#

No one even mentioned it

crude crater
#

"Dont giveaway code." "it is infact a big deal"

glacial echo
#

can i use the key half of a dictionary in a simialr manner to a list?

cyan nest
#

You did it first

#

Stop victimizing

crude crater
#

im not, i said what happened lol

cyan nest
#

He just told you no

crude crater
#

i asked if someone has a script for blacklisted words and i got a lecture

cyan nest
#

But you went and escalated

#

You know, why even bother

boreal ravine
#

If you spoonfeed others they won't learn how to do the thing they got spoonfeeded. That's what we're tryna tell you here

cyan nest
#

I'll just go back to sleep

crude crater
#

because he said "dont give free code" and i asked why and then i got chewed out for no reason

crude crater
crimson pulsar
#

hello

cyan nest
#

No one chewed you out

drifting arrow
crimson pulsar
#

whats happening here

crude crater
#

this was my first resource and now im just gonna do it myself its not that big of a deal

#

please drop it already dude

cyan nest
#

Point out one message where it did actually happene

crimson pulsar
#

!shh

unkempt canyonBOT
#

✅ silenced current channel for 4 minute(s).

tight obsidian
#

Hi people, let's not get into a heated debate over unimportant stuff

#

!unshhh

unkempt canyonBOT
#

✅ unsilenced current channel.

crude crater
#

thank you

crude crater
#

preciate it, now if anybody needs help just lmk :)

crude crater
drifting arrow
#

🤔

#

still need someone to review my code to see if I missed something.

glacial echo
#

can a dictionaries keys be used in a similar manner to a list?

crude crater
#

send it

drifting arrow
#

k

boreal ravine
slate swan
#

ohh

drifting arrow
#
#Kicks/Bans everybody who has an account less than 1 day old or who has joined within 24 hours.
@client.command()
@commands.has_role('bot')
async def raid(ctx):
    memberslist = []
    if ctx.channel.name == 'botstuff':
        for i in client.guilds:
            for member in i.members:
                if member.id != 832106800580001813:
                    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)
                        await member.send('Kicked due to anti-raid procedures. If you believe this is in error, feel free to contact our staff. <List of staff goes here> \n\n as this is just a test, you are not banned. The live version will ban you.')
                        await member.kick()

        await ctx.send('I have compiled a list of members who were kicked. Please note this list is only sent to help verify everybody who should have been kicked. \nI only check for accounts created or joined within the last 24 hours.')
        memberslist_string = 'tickticktick\n'
        for i in memberslist:
            for a,b in i.items():
                memberslist_string += (f'{a} : {b} \n')
            memberslist_string += ('\n')
     
        memberslist_string += 'tickticktick'
        await ctx.send(memberslist_string)
boreal ravine
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
slate swan
glacial echo
crude crater
#

no spoonfeeding happened but a lot of people were whining about spoonfeeding happening

boreal ravine
crude crater
#

NOW MOVING ON

drifting arrow
#

focus people. focus!

#

we're focusing on me right now

crude crater
#

yes

cyan nest
#

You know

crude crater
#

whats ur error?

drifting arrow
#

No error. just review

cyan nest
#

I'm honestly surprised that a silence didn't stop you guys

slate swan
#

lol

cyan nest
#

Take a deep breath or smth

glacial echo
#

im not it was like 4 minutes

crude crater
#

oh my lord leave it already dude 🤦‍♂️

cyan nest
#

What

#

No one is even talking to you

drifting arrow
#

Focus damnit!
@crude crater do you think i've missed anything? Can you spot anyways this could go wrong?

glacial echo
#

a channel purge and maybe some animal/pet pics would possibly work for a channel topic reset method

drifting arrow
#

Ty ty

crude crater
#

wait what is it even for?

#

because idek what im looking for lmfao

drifting arrow
#

So when a server gets raided, instead of sshing all channels, just purge everybody with an account <1 day old or joined <1 day ago

crude crater
#

oh for anti raid? thats sick!

drifting arrow
#

and the message is in case some innocent pleb gets caught in the kick/ban wave

crude crater
#

okay lemme look

slate swan
#

im pretty sure theres a better way

#

ive made one before but i forgot

drifting arrow
#

I'm happy to take suggestions on how to improve it if you can provide.

#

At the moment, the code works so far.. 'as intended'

crude crater
#

now personally i wouldnt do for people who JOINED in last 24h

#

but for accounts that were made in 24h

drifting arrow
#

as in the 20 people I tried it on, it worked as intended.

crude crater
#

imo

glacial echo
drifting arrow
crude crater
#

true

#

but where in the script does it kick the people?

glacial echo
crude crater
#

no

#

kick is sufficient i think

drifting arrow
glacial echo
#

which is great until a staff member changes their name or gets nitro

drifting arrow
#

If I stick to kick. I could just also send them a new invite?

crude crater
#

exactly

drifting arrow
#

Since most of those 'spam accounts' are just bots and wont have their pms checked anyway

glacial echo
#

i think a temp ban of some sort would be ideal as it would prevent people from spam joining?

crude crater
#

i think its great!

slate swan
glacial echo
#

nah like tempban 1 day

drifting arrow
#

i wouldnt do 1 day. I'd do maybe 5 minutes

crude crater
#

well if you're trying to prevent spam joining 15s is good i think

#

yeah 5 minutes is good too

glacial echo
drifting arrow
#

So changes:
1 - change kick to tempban 5 minutes
2 - Send a new invite link.

glacial echo
#

yeah

#

that works

#

oh even better actually, add an optional specification for how many minutes to tempban for, otherwise default to 5

drifting arrow
#

Now how the bot handle if the output..

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

Is longer than what discord allows? will it just send a txt file?

glacial echo
#

how many moderators we talking?

crude crater
drifting arrow
crude crater
#

oohhhh

#

like for the raid message? or just in general?

drifting arrow
#

Just in general

crude crater
#

oh

#

eh i feel like it could do without that personally

drifting arrow
#

I'm still testing it. and the output can be quite large

crude crater
#

true

drifting arrow
#

That was before I added the exception for the bot.

#

That output will be longer in a raid tho. So I am concerned that it may not send it if it's above the discord character limit

crude crater
#

itll be fine

drifting arrow
#

Will it send it as a txt file? 🤔

crude crater
#

you could edit the code to do that

#

but unless its banning id say like 50+ people itll be fine

bitter depot
#

fwiw we don't allow paid services of any kind. If you're going to help here, you do it for free

drifting arrow
#

The idea before the message being sent is so you as the admin can be like 'oh damn. I accidentally banned half the new staff members I invited today.'

drifting arrow
crude crater
#

you can always feel free to DM me if you're up for it too long

#

because they're pretty strict in this discord a lot of times lol

glacial echo
crude crater
#

but its for staff

drifting arrow
crude crater
#

and mods not the owner

drifting arrow
#

Owner is just the name of the role I had at the time xD

drifting arrow
glacial echo
#

it to me seems celaner than checking if its in a private testing channel

#

and is also useful for stuff like emergency reset commands and bot shutoff commands

drifting arrow
royal silo
crude crater
#

OH WAIT

glacial echo
royal silo
#

i am getting this response on image.attachments

crude crater
#

you could just attach a permanent invite to the message

royal silo
#

how do i get the url

drifting arrow
crude crater
#

because theres no way a raid bot is that advanced to click on a link

crude crater
crude crater
#

its a discord DM

#

its a totally different boat lol

glacial echo
drifting arrow
#

Looking into that now @glacial echo ty

glacial echo
#

alright tahts enough helping for now imma work on my thing

crude crater
#

cya

#

but yes i agree with Katte, it might not be that specific line obviously but to create a new invite is a perfect idea

elder python
#

how to get guild id from bot object

crude crater
#

because thats not how you do something to send to a channel

#

its

#

await ctx.send

#

you do it in brackets

#

await ctx.send("@hollow iron Bruh, did " + '<@' + {ctx.author.id} + '>' + " really just try that? Don't worry, he's banned lol!")

bitter depot
#

'<@' + {ctx.author.id} + '>' -- {ctx.author.mention} is a thing

#

And it needs to all be one f-string

#

e.gpy f"@hollow iron did {ctx.author.mention} really just try that?"

crude crater
elder python
#

whats the use of passing bot to callable when making a dynamic command prefix

#

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

#
def what_prefix(bot , message : commands.MessageConverter):
        db = get_database()
        collection = db["prefixes"]
        guild_id = message.guild.id
        result = collection.find_one({"_id": guild_id})
        if result is None:
            return "$"
        else:
            return result["prefix"]
bitter depot
#

callable just means a function in this case

elder python
#

is somethig wrong

drifting arrow
#

hhmm.

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

try this

elder python
bitter depot
glacial echo
#

is it incorrect?

bitter depot
#

message.author.id

#

It's in a command so ctx.author.id and you shouldn't even be doing that anyway

#

Just use ctx.author.mention as I said to them above

glacial echo
#

i dunno man i just took the code they had posted and offered a way to troubleshoot the problem they said?

#

but my apologies

drifting arrow
#

What happens if I invite people to a channel they dont have permissions to view?

#

do they just get sent to the nearest public channel?

#

Why not use fstrings @hollow iron ?

#

cool

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
#
@client.command(aliases=["SERVERINFO", "Serverinfo", "Serverinformation", "SERVERINFORMATION", "serverinformation"])
async def serverinfo(ctx):
        embed = Embed(title="Server information",
                      colour=ctx.guild.owner.colour,
                      timestamp=datetime.utcnow())

        embed.set_thumbnail(url=ctx.guild.icon_url)


        fields = [("ID", ctx.guild.id, True),
                ("Owner", ctx.guild.owner, True),
                ("Region", ctx.guild.region, True),
                ("Created at", ctx.guild.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
                ("Members", len(ctx.guild.members), True),
                ("Humans", len(list(filter(lambda m: not m.bot, ctx.guild.members))), True),
                ("Bots", len(list(filter(lambda m: m.bot, ctx.guild.members))), True),
                ("Text channels", len(ctx.guild.text_channels), True),
                ("Voice channels", len(ctx.guild.voice_channels), True),
                ("Categories", len(ctx.guild.categories), True),
                ("Roles", len(ctx.guild.roles), True),
                ("\u200b", "\u200b", True)]

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

        await ctx.send(embed=embed)
crude crater
keen talon
#

!fstring

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.

crude crater
#

like i type the command and then nothing happens

#

ctx.author

#

well what are you trying to do?

maiden fable
#

Yea

crude crater
#

yes but on what event?

maiden fable
#

But that will ban the person who invoked a command

bitter depot
crude crater
#

yes exactly

maiden fable
#

Imagine doing

async def on_message(message):
    await message.author.ban()
crude crater
#

ctx.author.ban*

drifting arrow
maiden fable
glacial echo
bitter depot
glacial echo
#

the important bit being the case insensitive thing

maiden fable
#

Who cares. It's optional

bitter depot
#
.ban(reason="reason")```
boreal ravine
#

awiat ctx.member.ban(reason=reason)

#

or that

glacial echo
#

whats the thing that lets commands still work even if i have an on_message() event?

bitter depot
#
await bot.process_commands(message)```in your `on_message`
slate swan
#
response = requests.get(url, headers=headers)
if response.status_code == 200:
    data = response.json()
    m = str(data['data']['attributes'])
    print(m)
else:
    print("Not wkrng")
#

error:```
m = str(data['data']['attributes'])
TypeError: list indices must be integers or slices, not str

bitter depot
#

That or data is a list

#

Try printing data and see what the output is

drifting arrow
#
@commands.has_role('bot', 'Bot', 'Owner')

This doesn't work. would I instead pass a list?

@commands.has_role(['bot','Bot','Owner'])

or would I just need to write that line multiple times?

slate swan
slate swan
bitter depot
#

Yeah, so data['data'] is a list

#

You can clearly see that in the image you sent

royal silo
slate swan
#

yes

bitter depot
#

It's a list, so you'd want to loop over it presumably

slate swan
#

yes

bitter depot
#
for whatever_you_want_to_call_it in data["data"}:
    print(whatever_you_want_to_call_it["attributes"])```
manic path
#

How would I update my dpy version?

bitter depot
manic path
#

ah

frosty prairie
#

how to send image in an embed message..

manic path
#

thank you

slate swan
glacial echo
drifting arrow
#

resolved my past issue. it's actually "has_any_role" 😮

frosty prairie
slate swan
#

umm use the pil lib?

waxen granite
#

anyone?

frosty prairie
#

..

slate swan
#

pillow lib

frosty prairie
#

lob

#

uh

slate swan
#

except MemberNotFound:
ctx.send("member not found")
gives me SyntaxError: invalid syntax, how come?

#

python
image manipulation
lib

#

pil

slate swan
#

message or msg

slate swan
#

depends on what you put

waxen granite
slate swan
#
@bot.command()
async def strike(ctx, member: discord.Member = None, *, reason=None):
    except MemberNotFound:
    await ctx.send("member not found")
    role = discord.utils.get(ctx.guild.roles, name="striker")
    if not role in ctx.author.roles:
        embed1 = discord.Embed(description='You do not have the role "striker".',
                               colour=0xff0000)
        await ctx.send(embed=embed1)
        return
    if member is None:
        embed1 = discord.Embed(description="The provided member could not be found or you forgot to provide one.",
                               colour=0xff0000)
        await ctx.send(embed=embed1)
        return

    if reason is None:
        embed1 = discord.Embed(description="Please provide a reason for striking this person.",
                               colour=0xff0000)
        await ctx.send(embed=embed1)
        return

    embed1 = discord.Embed(description=f"{member.mention} has been succesfully striked!",
                           colour=0x00ff00)
    await ctx.send(embed=embed1)``` full code
#

🤦‍♂️

frosty prairie
drifting arrow
#

How can I resolve this issue:

waxen granite
drifting arrow
#

So basically the string is over 4000 characters. How do I make it send as a txt file?

waxen granite
#

someone?

frosty prairie
brazen raft
#

Or just paginate the embed

frosty prairie
bitter depot
slate swan
bitter depot
#
await ctx.send(embed=embed, file=discord.File(...)```
slate swan
#

read above

bitter depot
#

If you're wanting to add an image you'd generally do embed.set_image

#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

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

..

waxen granite
#

tizzy help me :3

bitter depot
#

You can do url="file://full/path/to/file.png"

maiden fable
#

Some people say it doesn't work

frosty prairie
slate swan
floral jacinth
#
        await msg.edit("finito")```
why this code doens't work?
bitter depot
#

You're doing str(guild) instead of str(guild.id) from the looks of it.
str(guild) gives the name, not the id

waxen granite
#

hm

#

well it worked before

slate swan
#

try ```py
msg = await ctx.send("Comando in corso...")
await msg.edit(content = "finito")

bitter depot
bitter depot
slate swan
#

editing a mention doesnt work

bitter depot
#

I know, that's why I edited it in

#

I'd already mentioned them once

bitter depot
#

nvm then lol

floral jacinth
frosty prairie
slate swan
#

umm

frosty prairie
#

breh several people

bitter depot
#

Try attachment:// @frosty prairie

slate swan
#

use BytesIO?

maiden fable
#

As I said, I don't think that works in 2.0, @bitter depot

bitter depot
#
file = discord.File("output.png")
e = discord.Embed(...)
e.set_image(url="attachment://output.png")
await ctx.send(embed=e, file=file)```I found this online, worth trying ig
frosty prairie
#

but if i remove that.. mysql error doesnt come up wth sad

glacial echo
#

can i put all my commands in one @client.command() or does each thing need its own?

drifting arrow
#

Since my bot is in multiple discords. How do I limit my commands to only check the current discord the command was run in and not every discord?

drifting arrow
#

yeah lol

drifting arrow
#

I just realized it was checking the 2 discords it was in coz I removed some of the parameters

bitter depot
#
@bot.command()
async def ping(...):
    ...


@bot.command()
async def wave(...):
    ...

...```
glacial echo
#

i mean you should only need to cross reference the guild of the message with teh guild of the user right?

drifting arrow
#

Well I want to only run the command in the discord it was run in.
So say my bot is it this discord and say.. fortnite discord.
I dont want to ban everybody in fortnite because I ran the command here.

#

And vice versa

drifting arrow
#

Just remove the else section? Or give the else section some things to check. Like maybe message age or the last time it sent a "No giveaways going on in this channel"?

waxen granite
#

okay

glacial echo
#
if message.author.id in client.players[0]:
TypeError: argument of type 'int' is not iterable

what does iterable mean?

bitter depot
#

iterable basically means you can loop (iterate) over it

#

And you can't loop over an integer, which is what client.players[0] is

glacial echo
#

oh shoot thanks

bitter depot
#

Presumably you want
if message.author.id in client.players (is a player)
or if message.author.id == client.players[0] (is the first player)

glacial echo
#

that should be == right?

#

ah ok thanks

drifting arrow
#

geesh

boreal ravine
#

mhm

drifting arrow
#

hhmm i dont think I've missed anything yet

frosty prairie
drifting arrow
#

So you want a discord bot to send images?

frosty prairie
drifting arrow
glacial echo
#
@client.command()
async def joinGame(ctx):
  await ctx.message.delete()
  if ctx.author.id in client.players:
    await ctx.send(f'{ctx.author}, you are already in the game, no need to join twice.')
  else:
    await ctx.send(f'<@{ctx.author.id}> has joined the round!')
    client.players += [ctx.author.id]
    print(client.players)
@client.event
async def on_message(message):
  if message.content.startswith("b|") == False:
    try:
      if message.channel.id in list(client.channelGame.keys()):
        if message.author.id == client.players[0]:
          return
    except IndexError:
      print("Index out of range, probably empty still")
  await client.process_commands(message)

client.run(token)

running this, then typing b|joinGame always prints out the users username, even though no such print statement exists? unless im blind that is

frosty prairie
drifting arrow
#

I found a code online... and got this when I ran it:

Is this not what you want?

frosty prairie
#

i want smth like this

boreal ravine
#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
boreal ravine
frosty prairie
drifting arrow
#

OH he wants it inside the three code ticks

boreal ravine
boreal ravine
drifting arrow
#
my text
myimage goes here
more text
drifting arrow
boreal ravine
# frosty prairie yee
# Rewrite
file = discord.File("filename.png") # an image in the same folder as the main bot file
embed = discord.Embed() # any kwargs you want here
embed.set_image(url="attachment://filename.png")
# filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
await ctx.send(embed=embed, file=file)
``` this will help ^^
elder python
#

how to change nickname of bot using bot obj

boreal ravine
#

Get the channel ID you wanna send the message in then send it

boreal ravine
#
file = discord.File("monkey.png") 
embed = discord.Embed(title='Monkey')
embed.set_image(url="attachment://monke.png")
await ctx.send(embed=embed, file=file)
``` like this
frosty prairie
boreal ravine
#

Get the channel ID

#

Show your full code?

#

Show me your code

drifting arrow
#

Alright I managed to add the image. now to figure out how to attach text to it xD

frosty prairie
#

channel = client.get_channel('channelid')
await channel.send('hello')

frosty prairie
#

um

boreal ravine
frosty prairie
boreal ravine
frosty prairie
#

..

bitter depot
#

Or at least a lot of it

boreal ravine
#

yes

#

they are mostly outdated or don't work well

frosty prairie
#

:/

#

ok sorry

boreal ravine
frosty prairie
#

no errors either

boreal ravine
frosty prairie
#

imgur?

frosty prairie
drifting arrow
#
@client.command()
@commands.is_owner()
async def sendimage(ctx):
    # Rewrite
    file = discord.File("cow.png") # an image in the same folder as the main bot file
    embed = discord.Embed() # any kwargs you want here
    embed.add_field(name="text1", value="Hello World", inline="False")
    embed.set_image(url="attachment://cow.png")
    embed.set_thumbnail(url="attachment://cow.png")
    embed.add_field(name="text2", value="Hello World", inline="False")
    # filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
    await ctx.send(embed=embed,file=file)

How do I get the image above the second text field? 🤔

drifting arrow
#

So images are always at the end?

boreal ravine
#

yes

drifting arrow
#

damn

boreal ravine
#

i think?

bitter depot
#

avatar, icon, image and thumbnail can all take an image

frosty prairie
drifting arrow
#

But image is always at the end tho 😦

#

Oh well

boreal ravine
bitter depot
boreal ravine
bitter depot
#

Well it's not solely at the bottom like they said

#

It can also be at the top

drifting arrow
boreal ravine
dawn gale
#

how do i make hangman

boreal ravine
#

You make it

dawn gale
#

yeah but how

boreal ravine
#

You learn

frosty prairie
dawn gale
#

yeah but how

frosty prairie
#

..

dawn gale
#

how learn

boreal ravine
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.
drifting arrow
frosty prairie
boreal ravine
dawn gale
#

idk hto im new to server

frosty prairie
drifting arrow
dawn gale
#

how do i take input from the discord server in discord.py

boreal ravine
frosty prairie
boreal ravine
slate swan
dawn gale
#

why are so many people called !

boreal ravine
drifting arrow
frosty prairie
#

its like dis..

slate swan
#

Never mind. One way is to put the file path

frosty prairie
glacial echo
#
if message.channel.id in list(client.channelGame.keys()) and channelGame.get(message.channel.id) == 1:

i ahve the following statement, but im getting a red line under the second portion of the statement, but somethign is bugging out and i cant properly hover over any of the text in that portion to see any error messages

#

what might be wrong with it

bitter depot
#

There's nothing blaringly wrong with that if statement

#

Although you don't need to convert the .keys() into a list just for an in check

glacial echo
#

ah

#

ohhh its me once again being stupid and forgetting that my variables are all client.variable

#

cause i was having weird problem where i couldnt write to a variable and use it elsewhere in teh code

bitter depot
#

variables defined inside a function don't exist outside of them

#

So yeah, you have to use a bot-attr

#

!tag bot

unkempt canyonBOT
#

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

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

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

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

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

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

bitter depot
#

There we go lol

#

Also please change your definition to bot = commands.Bot and not client = commands.Bot

#

The latter is such bad practice

slate swan
#

So, has there been any new maintained library with slash commands yet?

bitter depot
#

client = commands.Bot is like doing my_integer = "some string", it's just completely misleading @glacial echo

glacial echo
#

oh

#

alirght ill do that at some point soon

bitter depot
#

If you're using a decent IDE it should have a refactor option that allows you to change all instances of the variable at once

glacial echo
#

im not even using a respectable IDE

#

im using repl.it because im an idiot

bitter depot
#

Rofl

#

You're just going to get random ratelimits

#

Everyone who hosts bots on repl.it basically shares the same IP, and so not only do you get ratelimits from your code, but also from everyone else who's hosting a bot at that time @glacial echo

glacial echo
#

oh fr?

bitter depot
#

yeah lol

glacial echo
#

i did not know that at all

bitter depot
#

I mean it's not quite everyone on the same IP but the IPs are shared between multiple people

glacial echo
#

i havent had any issues with it but ill switch over i guess

bitter depot
#

You reall should switch to a proper IDE

glacial echo
#

i was honeslty just using it cause i found it easy to share projects and stuff

#

when i was working with a few other people

#

and now its just a bad habit

drifting arrow
# frosty prairie i wanna send a image which is in the file in an embedded form
@client.command()
@commands.is_owner()
async def sendimage(ctx):
    # Rewrite
    file = discord.File("C:/Users/[myname]/Desktop/discordbot/Discordbot/Discordbot/cow.png", filename="fish.png") # an image in the same folder as the main bot file
    embed = discord.Embed() # any kwargs you want here
    embed.add_field(name="text1", value="Hello World", inline="False")
    embed.set_image(url="attachment://fish.png")
    embed.set_thumbnail(url="attachment://fish.png")
    embed.add_field(name="text2", value="Hello World", inline="False")
    # filename and extension have to match (ex. "thisname.jpg" has to be "attachment://thisname.jpg")
    await ctx.send(embed=embed,file=file)

Change the location of the image to wherever it is your image is. the filename is the reference to the sed_image and set_thumbnail, it can honestly be whatever you want.

bitter depot
#

If you want to share it easily I guess you can always zip the code

glacial echo
#

by share i mean it was more simple than constant pull requests and merging and branches on a github repo

drifting arrow
#

What are you trying to do?

#

oh

bitter depot
drifting arrow
#

@hollow iron is there a specific condition?

glacial echo
#

ah yes pycharm, the thing smart python devs use

bitter depot
#

Like I've been contributing to @unkempt canyon quite a bit recently, and PyCharm just makes it so easy with its built-in git features

glacial echo
#

i use Intellij with a python plugin

drifting arrow
#

As in. What needs to happen for the bot to send a message to the channel?

glacial echo
#

for reasons

bitter depot
glacial echo
#

i would but i really dont need another IDE

#

ive already got like 3

bitter depot
#

Trust me PyCharm is 1000% worth it

#

As long as you have enough RAM (8gb min, ideally 16gb)

glacial echo
#

oh im not arguing that, i know its worth it i used to use it at school

frosty prairie
#

how do we do this ..

#

:/

storm zodiac
#

how can i get the cog's subcommands in help?

glacial echo
#

oh god i dont like having my token as plaintext

frosty prairie
#

how to react to a message..

waxen granite
willow vine
#

how do i remove the command from the content of command

spring flax
unkempt canyonBOT
#

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

Add a reaction to the message.

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

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
willow vine
#

like when i use a command

waxen granite
willow vine
#

the content of the message is the entire command with prefix and command name

#

i dont want that in the message content

glacial echo
#

code?

waxen granite
#

fetch the channel using its id

slate swan
drifting arrow
#
@client.command()
@commands.is_owner()
async def msgchan(ctx):
    channel = client.get_channel(794837147068792865)
    await channel.send('Hello')
#

@hollow iron enable developer mode on discord, right click channel and copy id

waxen granite
storm zodiac
drifting arrow
#

@hollow iron

@client.command()
@commands.is_owner()
async def msgchan(ctx, chanid):
    channel = client.get_channel(int(chanid))
    await channel.send('Hello')

if you want to be able to specify the channel id with the command

#

also @hollow iron 'client' could also be bot. it's whatever you specify here:

client = commands.Bot(intents=intents,command_prefix = '$')
upbeat otter
#

Guys, I am making a command for DM with my bot, and when the user writes a message, the message is sent in a server channel anonymously, can i add a button that can direct the user to that specific channel?

frosty prairie
drifting arrow
#

wot

#

Does the bot have permissions to view and send messages to that channel?

#

oh

#

you're passing the id as a string.

#

pass it as an int

#

also dont indent

#

try this

vrbl = Bot.get_channel(886511773753147412)
await vrbl.send('yo')
glacial echo
#

why is pep 8 so strict???

drifting arrow
#

change vrbl to channel

wooden frigate
#

Who uses pycord?-

drifting arrow
#

@hollow iron i honestly have no idea at this point. I've sent you everything that works and somehow it's not working for you.

@client.command()
@commands.is_owner()
async def msgchan(ctx):
    channel = Bot.get_channel(886511773753147412)
    await channel.send('Hello')

This should work, but I just don't know anymore. if it doesn't work for you then you've gone wrong somewhere.

maiden fable
maiden fable
glacial echo
#

it throws a fit when i have a space to seperate my dict entries from teh :

#

pep 8 is like an overbearing parent

maiden fable
#

Haha

drifting arrow
glacial echo
#
@client.event
async def on_message(message):
    if message.content.startswith("b|") == False:
        try:
            if message.channel.id in client.channelGame.keys() and client.channelGame.get(message.channel.id) == 1:
                if message.author != client.user and message.author.id in client.players:
                    if message.author.id == client.players[0]:
                        if len(message.content) <= 45 and " " not in message.content:
                            client.remainingCharacters = len(message.content)
                            while client.remainingCharacters > 0:
                                for i in message.content:
                                    for key in pointDict:
                                        if i == key:
                                            client.points += pointDict[key]
                                            client.remainingCharacters -= 1
                            await message.send(client.points)
                            client.points = 0
                            client.players.insert(0, client.players.pop())
                            await message.send(client.players)

        except IndexError:
            print("Index out of range, probably empty still")
    await client.process_commands(message)

is there a contradiction in here somewhere?

#

it registers teh person joining the game, it registers the game channel, but it wont send any messages about points

maiden fable
#

Try adding print statements and see which ones are triggered

glacial echo
#

hmmm literally none of them

maiden fable
#

?

glacial echo
#

nothing triggered at any point

#

i think its my dictionary key search

#

does message not have a .channel.id?

maiden fable
#

It should print

#

!d discord.Message.channel

unkempt canyonBOT
maiden fable
unkempt canyonBOT
ionic wadi
#

I am currently making an advertisement command, and a question is how many members It has.

I want It to detect the message.content but how can I do that?
I currently have:

if message.content.lower() <150:
return await ctx.send("We dont accept servers under the needed 150 members.")

#

But It doesnt detect the number or atleast, theres no error or output

glacial echo
#

whats your code?

#

oh oh oh

#
try:
  if int(message.content) < 150:
    do stuff
except:
  something do on broken
waxen granite
glacial echo
#

should convert your message to a int which can be compared to another int

waxen granite
#

Help!!!

lament mesa
#

!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.
ionic wadi
#

File "/home/container/bot.py", line 771
@bot.command()
IndentationError: unexpected unindent

why>

drifting arrow
ionic wadi
#

{ctx.author}

#

euhm

drifting arrow
#

you as in server owner?

#

or you as in, just always youj regardless of role?

#
@client.command()
async def spamvaprant(ctx):
    vaprants_id = 672580539513045013
    await client.send_message(vaprants_id, 'Spam spam spam')

You don't need 'vaprants_id' However it's there so u understand

ionic wadi
#

!codeblock

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.

ionic wadi
#
@bot.command()
@commands.dm_only()
async def partner(ctx, leden=None):
    await ctx.send("Bedankt voor het aanvragen van een partnership! Hoeveel leden heeft u?")
    try:
        message = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=45.0)
    except asyncio.TimeoutError:
        await ctx.send("Helaas reageerde je niet binnen 45 seconde! En de prompt is beeindigd.")
    else:
        try:
            if int(message.content) < 150:
                return await ctx.send("We accepteren helaas geen partners onder de 150 leden.")
            if int(message.content) > 150:
                await ctx.send("Top! Hier komt dan de rest van de cmd")
                return
        else:
            await ctx.send("Error, geen geldig nummer gevonden.")```

  File "/home/container/bot.py", line 768
    else:
    ^
SyntaxError: invalid syntax
drifting arrow
#

Actually doesn't work. apparently not /shrug

slate swan
#

else without if

#

then the indentation on the other else

drifting arrow
slate swan
#

it's meant to be, but it's still an else without an if

drifting arrow
#

The best kind of truth

ionic wadi
#

${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
File "/home/container/bot.py", line 763
int(message.content) < 150:
^
SyntaxError: invalid syntax

slate swan
drifting arrow
#

Yeah I know. I said that a while ago.

slate swan
#

!d discord.TextChannel.send

unkempt canyonBOT
#

await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=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/stable/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/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
drifting arrow
slate swan
#

wtf

#

kinda

slate swan
#

it's still just going to do that unless someone takes over the project

drifting arrow
#

Well. discordpy will continue to work until discord itself updates the api

#

or until python updates and python commands are deprecated.

#

Whichever happens first

#

So we still have time

lament mesa
slate swan
#

but this has given me motivation to start something else

drifting arrow
lament mesa
#

lol

slate swan
#

forks > spoons

native harness
#

Hello,
I have a bot and I would like it to leave all servers that dont have their ID's inside a certain file. How do I get the ID's of the servers my bot is in and how to make it leave them?

slate swan
unkempt canyonBOT
slate swan
#

!d discord.Guild.leave

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.delete "discord.Guild.delete").
native harness
#

so i do leave(id)

#

?

slate swan
#

no

#

you do await guild.leave()

native harness
#

oh okay

#

guild being an ID?

#

or i have to use utils.get

slate swan
#

guild being a guild object

#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
native harness
#

ooo i see

#

so how do i get a list of servers the bot is in?

drifting arrow
#

would this world?

for i in guild.id:
    if i != 1234:
      guild.leave()
slate swan
#

NEED HELP
This is my code.

import os
import discord
from discord.ext import commands
import music

Client = commands.Bot(command_prefix = '§', intents = discord.Intents.all())

cogs = [music]

for i in range(len(cogs)):
cogs[i].setup(client)

@client.event
async def on_ready():
print(f"{client.user} logged just in!")

my_secret = os.environ['TOKEN']
client.run(my_secret)

#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
#

got like 3 erros

lament mesa
native harness
lament mesa
slate swan
#

a list of guild objects, yeah

native harness
lament mesa
#

no

native harness
slate swan
drifting arrow
native harness
#

thanks alot guys

slate swan
lament mesa
#

bot.guilds returns a list of discord.Guild objects

drifting arrow
# slate swan for i in range(len(cogs)): cogs[i].setup(client)
@client.command()
@commands.is_owner()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
@commands.is_owner()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')


for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')
ionic wadi
lament mesa
#

!d discord.Client.guilds

unkempt canyonBOT
slate swan
#
for guild in bot.guilds:
    if guild.id != 1234:
        await guild.leave()
#

like this somehow

native harness
drifting arrow
drifting arrow
slate swan
drifting arrow
#

If it works it works

lament mesa
drifting arrow
#

Gah

#

took jumper off coz hot. now am cold D:

clever wind
#

i get a malformed disk image for my database when replit tab closes or crashes. if i close the database, would the database be fine even after replit crashing/closing?

slate swan
#

with ur code

drifting arrow
#

did you remember to change 'client' to whatever you specified at the start? client = commands.Bot(intents=intents,command_prefix = '$')

drifting arrow
#

yours might be bot or BOT or Bot or BOt or bOT or boT

lament mesa
drifting arrow
#

@lament mesa problem is tho. people keep using Bot or bot and im here using client and they get confused ;-;

slate swan
#

how to bot join welcome messageeeeeeeeeee

drifting arrow
elder python
#
@bot.listen('on_message')
async def whatever_you_want_to_call_it(message):
    # do stuff here
    # do not process commands here

here waht does 'do not process commands here' mean?

slate swan
#

use @bot.command()

slate swan
#

instead of using if statements there

lament mesa
clever wind
#

it just leads me to this channel

slate swan
#

yeah read what the bot said bru

drifting arrow
drifting arrow
#

So there is a standard

lament mesa
#

Lets say you have a class named Foo you won't name the instance bar right?

slate swan
#

bet

drifting arrow
#

idk, im weird. but probably not

lament mesa
#

The same applies to commands.Bot

drifting arrow
#

How did you get that darkened background on that text?

lament mesa
#

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

drifting arrow
#

whenever i do that I cant do it inline.

slate swan
#

Is there any event that has anti nuke like on_guild_channel_create i dont know how to use it

#

whats the problem

storm zodiac
slate swan
#

His should be client

#

capital e

upbeat otter
#

Guys, i changed the name and the pfp of my bot, does it take time to get changed on the server?

slate swan
#

guys how to make bot send message when it joins a server

storm zodiac
slate swan
#

on_guild_join

slate swan
# slate swan

you need to define client as a bot instance or a client instance
its suggested to use a bot instance AND name it as a bot instance
suggested: py from discord.ext import commands bot = commands.Bot()Or you can use a client instance client = discord.Client()

storm zodiac
slate swan
#

Guys

upbeat otter
#

yes guys?

#

ask guys?

slate swan
#

How to kick a user that makes to many channels using the on_guild_channel_create

upbeat otter
slate swan
upbeat otter
# slate swan

bot = commands.Bot(command_prefix="Your prefix here", intents=discord.Intents.all())

upbeat otter
#

and use your prefix instead of your prefix here

slate swan
upbeat otter
upbeat otter
#

lmao

slate swan
unique nexus
#

it doesnt mention channel

slate swan
#

find what should i define it with

unique nexus
#

how to mention it then

slate swan
slate swan
#

should it be @bot.client

#

@slate swan we wont spoonfeed more

zenith zinc
#

Afk command who knoww

slate swan
#

learn basic python before trying to use discord.py
dpy is not at all a beginner friendly library

upbeat otter
#

u are making client.command() bro

upbeat otter
#

i made one....

#

but,....

zenith zinc
unique nexus
slate swan
slate swan
slate swan
slate swan
#

also it doesnt meantion in title i believe

unique nexus
#

🥲

slate swan
unique nexus
#

ok

steep estuary
#

what is the problem

#

my bot is going offline

#

:(

slate swan
#

@tawdry perch look there is a even called on_guild_channel_create that checks if any channel has been made how do i kick a user that makes to many

#

Like if channel.guild > 7:
Ban

#

Somethi like that

#

Can u paste the source here

#

Like for this event

#

Ok

#

Alright ill look at it brb

oak quest
#

MAKING A DISCORD BOT FOR Digimon or Pokemon

Hi I wanted to ask you if you wanted to help making this bot
I have made a discord bot in the past but this time I want someone that could help me
Kinda... I need someone that could be my second hand and contribute in making the bot
The bot is gonna be written in Python
If you are intrested come to my DM.

unkempt canyonBOT
#

6. Do not post unapproved advertising.

oak quest
#

i didn't advertise ?

#

what ?, i'm asking for help, that is not advertising afaik

slate swan
#

Well not really can u give me a sample

zenith zinc
#

i need help

#

pls dm

gloomy coral
#

Guys

#
@bot.command(aliases=["checkcogs", "check"])
async def checkcog(ctx):
    author = ""
    if ctx.author.id == 815555652780294175 or ctx.author.id == 723032217504186389:
        if ctx.author.id == 815555652780294175:
            author = "Mr One"

        elif ctx.author.id == 723032217504186389:
            author = "Mr Zero"

        for filename in os.listdir('./cogs'):
            all_cogs=[]
            loaded_cogs=[]
            if filename.endswith('.py'):
                print(filename[:-3])
                all_cogs.append(filename[:-3])
                print(all_cogs)
        await ctx.send(f"Hey {author} All cogs are [{''.join(all_cogs)}]")

        for i in all_cogs:
            try:
                bot.load_extension(f"cogs.{i}")
                await ctx.send(f"{i} wasn't loaded")
                await asyncio.sleep(1)
                bot.unload_extension(f"cogs.{i}")
            except commands.ExtensionAlreadyLoaded:
                loaded_cogs.append(i)

        await ctx.send(f"Hey {author} All loaded cogs are [{''.join(loaded_cogs)}]")
#

Why is this giving me an error?

#

Its returning

slate swan
#

Off that command

gloomy coral
slate swan
#

Look when the user makes more channels then the limit it should kick him can u do that?

#

Yes like just the on_channel_create part

#

Thats all

#

Na

boreal ravine
#

@gloomy coral imagine using bot

boreal ravine
unique nexus
#

I FIXED IT WITH des

slate swan
#

Well how do i kick

#

The user

boreal ravine
#

@slate swan rtfm for the events member join/removed

slate swan
#

That makes more then the limit

hasty iron
#

the one who created the channel?

slate swan
#

More then the limit

#

Ye

hasty iron
#

if so, you'll need to check the audit logs

gloomy coral
hasty iron
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

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

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print('{0.user} did {0.action} to {0.target}'.format(entry))
```...
gloomy coral
#

can sm1 help me pls

boreal ravine
#

@gloomy coral the thingy u defined commands.Bot for :)

slate swan
gloomy coral
#

..

boreal ravine
hasty iron
slate swan
hasty iron
#

you can filter the audit logs using action=AuditLogAction.channel_create

#

no

#

i said the iterator returns it

hasty iron
#

there are even examples on how to use it

slate swan
#

Can u just make a the whole code that would be easier to understand

hasty iron
#

no i cant "just make the whole code"

#

that's spoonfeeding

gloomy coral
#

@hasty iron cld u help me?

hasty iron
#

what error do you get

gloomy coral
#

see

#

theres no error it only shows one file

hasty iron
#

ok

slate swan
gloomy coral
hasty iron
#

sorry to disappoint you, but i don't have clairvoyance

#

i don't know what you expect or what you need

#

and i am supposed to "fix"

#

sure man

zenith zinc
#

How to react on messages..... lile of they type: a/invite, bot should react with a ✅ help in dm plss

hasty iron
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Add a reaction to the message.

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

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
zenith zinc
#

thanks

zenith zinc
hasty iron
#

how about

#

you send the code

#

and the error you get

#

and then we'll see "how dont work"

zenith zinc
#

ok

#

u see

visual island
#

should be a string

dapper cobalt
#

I will ask you one thing. How is it supposed to know what to add a reaction to?

dapper cobalt
zenith zinc
#

pls u help me @hasty iron

hasty iron
#

read what the two people above said

zenith zinc
velvet crest
#

Hmm so how can i make custom commands what's the ideology behind ... its like a user creates a command with some text and invokes it normally eg: !cc create test hello there and then the user will do !test and thr bot eill respond hello there... im ready to make it but i need the logic behind that how can i invoke it as a normal cmd

steep estuary
#

how i can solve this problem

dapper cobalt
zenith zinc
#

#

this

dapper cobalt
#

Not what reaction, what are you reacting to?

zenith zinc
#

on messgae

#

message*

dapper cobalt
#

Which message?

#

The ctx.message?

zenith zinc
#

dm

velvet crest
# zenith zinc

Do
msg = await ctx.author.send("ur stuff")
await msg.add_reaction("emoji")

dapper cobalt
#

He wants to react to the ctx.message.

velvet crest
dapper cobalt
#

That will react to the message that the bot sent not you.

velvet crest
#

he said dm msg

hollow summit
#

help i get this error

dapper cobalt
hollow summit
#

im doing erro handling in a cog

zenith zinc
#

not eork bro

vale root
#

With my say command how do i make what i said get deleted but the bot still says it?

slate swan
# zenith zinc

in the third line, i.e. the line after async def invite()
put msg = await ctx.auth...

fervent surge
#

ok, so when making slash commands with discord-slash(whatever), how long does it take for. the / commands to register?

vale root
zenith zinc
#

auuuuu

slate swan
zenith zinc
#

thank

vale root
slate swan
#

above or below your chocie
it will be executed in the order you put it

hollow summit
steep estuary
#

how i can fix this problem

dapper cobalt
hollow summit
steep estuary
#

i want if a user don't have that role bot should tell him that you must have a role with that name

dapper cobalt
boreal ravine
#

!d discord.ext.commands.MissingRole

unkempt canyonBOT
#

exception discord.ext.commands.MissingRole(missing_role)```
Exception raised when the command invoker lacks a role to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")

New in version 1.1.
steep estuary
#

not working

velvet crest
# zenith zinc

Before the await ctx.author .send add msg =
So it becomes msg = await ctx.author.send("stuff")

dapper cobalt
boreal ravine
vale root
#

How Do i add a reaction to my embed?

steep estuary
slate swan
#

@tawdry perch

#

dms

hollow summit
#

yh thats why i used hastepaste

steep estuary
dapper cobalt
#
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingRole):
    await ctx.send(f"You need `{error.missing_role}` role to use this command")
boreal ravine
#

yes

dapper cobalt
#

It checks if you meet the requirements to use the command and if you don't the checks aren't passed.

boreal ravine
steep estuary
#

oo

dapper cobalt
#

You can't get into a party without a ticket, you can't ban a member without ban_members permissions.

dapper cobalt
steep estuary
boreal ravine
#

oo👍

dapper cobalt
#

If you don't know such very basic things I highly suggest you learn Python before jumping into an advanced library like discord.py.

slate swan
#
@client.event
async def on_guild_channel_create(channel):
      try:
        guild = channel.guild
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
        logs = logs[0]
        reason = "Created More Channels Then The Limit"
        await logs.user.kick(reason=f"{reason}")
        await channel.delete()
      except Exception as e:
        print(e)``` guys how do i fix this error
'User' object has no attribute 'kick'
dapper cobalt
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#
@client.event
async def on_guild_channel_create(channel):
      try:
        guild = channel.guild
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_create).flatten()
        logs = logs[0]
        reason = "Created More Channels Then The Limit"
        await logs.user.kick(reason=f"{reason}")
        await channel.delete()
      except Exception as e:
        print(e)```
#


'User' object has no attribute 'kick'```
dapper cobalt
pale turtle
slate swan
dapper cobalt
slate swan
#

it says None

dapper cobalt
#

Try to print logs.user.id.

slate swan
#

yes it does print my id

dapper cobalt
#

All I can assume is that the user is not in the guild's members, or you don't have member intents enabled.

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

nop

#

i aint got that

dapper cobalt
#

Then do it and it should work.

slate swan
zenith zinc
#

!discord coinflip

#

!discord.coinflip

#

khm

#

helppppp

#

!coin

#

!coinflip

#

How to make coin flip command

boreal ravine
#

@zenith zinc No spamming pls

open forge
#

Make a random number generator

zenith zinc
boreal ravine
gleaming torrent
#

so Im trying to make my clear command clear users for specific users, like -clear user amount

zenith zinc
#

!userinfo

hasty iron
#

#bot-commands

zenith zinc
#

sorry

#

bro

gleaming torrent
#

so I'm trying to make my discord bot clear messages for specific users, like -clear user amount

hasty iron
#

ok

gleaming torrent
#

but I don't know how to make it clear for the user

hasty iron
#

use the check argument of TextChannel.purge

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=None, 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/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.

Examples

Deleting bot’s messages
boreal ravine
#

What do you check for?

hollow summit
#

how would i got about counting the messages a discord user has sent and making my bot display them

hasty iron
#
def is_me(m):
    return m.author == client.user

deleted = await channel.purge(limit=100, check=is_me)
await channel.send('Deleted {} message(s)'.format(len(deleted)))
``` here is an example from the doc page, just replace `client.user` with your Member or User object
boreal ravine
#

member == member? @hasty iron

native harness
#

Theoritically speaking, this code should work right?

#
@client.event
async def on_ready():
    print('bot initialized!')

    pre_serversallowed = varsfile.serversload()
    serversjoined = client.guilds
    serversallowed = []
    
    index_ = pre_serversallowed.keys()
    for I_ in index_:
        serversallowed.append(client.get_guild(pre_serversallowed[I_]))
    
    index_ = serversjoined.keys()
    for I_ in index_:
        if serversjoined[I_] in serversallowed:
            pass

        else:
            client.serversjoined[I_].leave()```
#

The goal is to leave servers that dont have their ID's in the file

#

that is imported

#

in varsfile.serversload()

novel rampart
#

did any one knows how to host discord.py bot host on HEROKU

#

any good youtube videos

native harness
#

No idea sry mate

hasty iron
#

heroku is not for discord bots

novel rampart
#

then

#

it is also host discord

#

bot

hasty iron
#

what

boreal ravine
#

pov: indians

#

no offence

stark bobcat
#

😂

gleaming torrent
#

heya, how can I make my discord bot delete peoples messages after they leave?

hasty iron
#

soft-ban?

#

ban them and then unban them

grand anvil
#

hi I need help. How to add timestamp if I have the unix time

gleaming torrent
#

but then my ban command will be useless

valid niche
#

you mean completely wipe all messages when the user leaves on their own?

gleaming torrent
#

yeah

#

delete messages for people that left

boreal ravine
valid niche
#

you either need to ban them with deleted days set to max, but this is limited in days

#

or you need to iterate over EVERY channel in the discord and EVERY message, which is a TON of API calls and can last months to finish if you have quite a lot of messages (a long time user for instance) and check who the author is

gleaming torrent
#

wait I think I know how to solve this

valid niche
vale root
#

why is my snipe command not working all its saying is There is nothing to snipe

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

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

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

!d datetime

unkempt canyonBOT
#

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

vale root
#

wait

#

indenet?

boreal ravine
# grand anvil hi I need help. How to add timestamp if I have the unix time
def to_timestamp(timestamp: int, typ: str = None):
  if not isinstance(timestamp, int):
      try:
        timestamp = int(timestamp)
      except ValueError:
        print("Invalid Timestamp Given: {}".format(timestamp))
  if not typ:
    return f"<t:{timestamp}>"
  if typ not in ["f", "F", "d", "D", "t", "T", "R"]:
    print("Invalid Type Given: {}".format(typ))
  return f"<t:{timestamp}:{typ}>" 
``` Got this from R. Danny ^^
valid niche
grand anvil
#

wait I meant like embed timestamp

hasty iron
#

if you have rdanny code, you need to make your bot open source and add the license

valid niche
#

read the license

valid niche
#

read the license

grand anvil
#

but it doesn't help me

boreal ravine
#

on the github?

grand anvil
#

I need like the one it shows in embed on bottom

hasty iron
#
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
valid niche