#discord-bots

1 messages · Page 573 of 1

slate swan
stiff nexus
#

which is that cmd when i delete the msg where i used that cmd the response also gets deleted

left wind
#

can you edit images with this?

echo wasp
slate swan
#
    async def on_member_join(self, member):
        channel = self.bot.get_channel(903695632877895693)
        await channel.send("Welcome!", member)```
#

why is it that when I try to send the message

#

it comes up with this error : send() takes from 1 to 2 positional arguments but 3 were given

lapis lintel
#

This channel is for Python, not javascript

dapper cobalt
lapis lintel
slate swan
slate swan
lapis lintel
#

It should be something like:

@commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(903695632877895693)
        await channel.send(f"Welcome {member.mention}!")
#

For example

lapis lintel
unkempt canyonBOT
lapis lintel
#

It should be working now, tho

slate swan
#

Thanks !

shut axle
left wind
hazy fulcrum
#

can someone add my bot into my server, i am on my school computer, at school, and discord.com is blocked. i have an unblocker for discord but hcaptcha doesnt show on this. so I cant verify.

reef shell
#

Don't break your school rules

#

Simple

hazy fulcrum
#

shut it

shut axle
#

@dapper cobalt ```py
from discord.client import client

reef shell
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
manic wing
reef shell
#

uppercase

shut axle
#

HOkay

left wind
#

can you edit images that are attached to a message with message.edit()

stiff nexus
#

which is that cmd when i delete the msg where i used that cmd the response also gets deleted

left wind
#

ive seen some people doing it on a bot tho prayge

manic wing
#

@shut axle do from discord.Client import run and then do py if name != "__main": import os os.system(await run)

#

thats how you maake a bot

shut axle
#

@manic wing it shows me that client is not defined.

stiff nexus
#

help??

manic wing
#

🤦‍♂️

reef shell
#

!d discord.Client.run

unkempt canyonBOT
#

run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").

Roughly Equivalent to...
reef shell
#

Cringe

manic wing
#

this is the true way to do imports

dapper cobalt
#

print(os)

reef shell
#

.....

#

I-

dapper cobalt
#

You imported os twice?

manic wing
dapper cobalt
#

!e

import os
print(os)
# I just need to know what the heck this actually prints.
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

<module 'os' from '/usr/local/lib/python3.10/os.py'>
slate swan
#

My brain is not working

manic wing
dapper cobalt
reef shell
stiff nexus
#

which is that cmd when i delete the msg where i used that cmd the response also gets deleted

#

HELP?

reef shell
#

trolling != misleading beginners

slate swan
stiff nexus
#

bruh what?

#

@slate swan wtf is this

slate swan
#

code:

async def whois(ctx,user:discord.Member=None):
    if ctx.channel.id != 835236006713098304:
        async with ctx.typing():
            await asyncio.sleep(0.4)

        emb2=discord.Embed(color=0x2f3136)
        emb2.add_field(name="Nickname:", value=f"`{user}`")
        emb2.add_field(name="ID:", value=f"`{user.id}`")

        await ctx.send(embed=emb2)
        return

Why doesn't my bot write anything?

slate swan
stiff nexus
#

now...

slate swan
manic wing
#

and this is inside of a command?

slate swan
dense swallow
#

Did u call the command?

dapper cobalt
#

Ah, nvm.

slate swan
stiff nexus
slate swan
slate swan
dense swallow
#

He asked how did u use the command

slate swan
#

clear

stiff nexus
#

like: ?whois @user ?

stiff nexus
slate swan
stiff nexus
#

which part?

dense swallow
#

Can u send the whole code

#

Including the cmd decorator

slate swan
#

from the main code "whois"...

manic wing
#

there are many ways to evaluate what might be incorrect;
a) put a print at the start, to see if it triggers; dot prints around, to see where it ends
b) revisit an error handler, maybe there is an error that we are missing.
c) print(ctx.channel.id)
d) check perms for the bot, maybe you catch discord.HTTPException's

stiff nexus
#

^^

#

@slate swan u have a error handler?

slate swan
stiff nexus
#
async def whois(ctx,user:discord.Member=None):
    if user is None:
      user = ctx.author
    if ctx.channel.id != 835236006713098304:
        async with ctx.typing():
            await asyncio.sleep(0.4)

        emb2=discord.Embed(color=0x2f3136)
        emb2.add_field(name="Nickname:", value=f"`{user}`")
        emb2.add_field(name="ID:", value=f"`{user.id}`")

        await ctx.send(embed=emb2)
        return
#

do this

#

edited it ^^^

dapper cobalt
dense swallow
#

Yes

dapper cobalt
#

If user is None it will take ctx.author; hence None is pretty much equal to False.

stiff nexus
#

ik but that guy dont know what that will do so i did like that....

dense swallow
#

Hmm

#

@slate swan Are u using this in main file or in a cog?

stiff nexus
#

main file

#

coz there is not self

slate swan
dense swallow
#

Are u using bot or client

dapper cobalt
#

Does it show that the bot is typing, tho?

stiff nexus
#

ahh anyone help me now.....?

slate swan
#

yes?

dense swallow
#

if ik I can help lol 😂

slate swan
echo wasp
#

can someone help with an error with discord bot with an equal sign and ModDeleted not defined?

dense swallow
#

Clear command?

stiff nexus
stiff nexus
dense swallow
#

Then?

dapper cobalt
#
async def whois(ctx, member:discord.Member=None):
  member = member or ctx.author
  if ctx.channel.id == 835236006713098304:
    return await ctx.send("You cannot use that here!")

  embed = discord.Embed(color=0x2f3136)
  embed.add_field(name="Nickname", value=user.nick)
  embed.add_field(name="ID", value=user.id)
  await ctx.send(embed=embed)

Try that.

slate swan
dapper cobalt
#

Oh that was your issue, not his.

stiff nexus
#

the cmd of @unkempt canyon like when i use that cmd and i delete the invoked message the bots reply also get deleted

dapper cobalt
#
msg = await ctx.reply("You cannot use that here!")
await asyncio.sleep(5)
await msg.delete()
await ctx.message.delete()
dense swallow
#

await ctx.message.delete() ?

#

^

dapper cobalt
#

You can also pass delete_after attribute to ctx.reply.

dense swallow
#

Yup

echo wasp
#

can someone help with an error with discord bot with an equal sign and ModDeleted not defined?

stiff nexus
dense swallow
#

delete_after=second

dense swallow
stiff nexus
#

let me show

dense swallow
#

k

stiff nexus
#

see:

#

!e test

unkempt canyonBOT
#

@stiff nexus :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'test' is not defined
stiff nexus
#

like that

echo wasp
echo wasp
stiff nexus
#

what is ModDeleted

echo wasp
stiff nexus
#

ik the event lol but how to know they invoked the cmd

stiff nexus
echo wasp
stiff nexus
#

ok

dense swallow
#

I haven't used it in my bot.. I think u call the event, the do smth like if author msg is deleted then delete bot msg

echo wasp
stiff nexus
#
@client.event
async def on_message_delete(message):
        channel = client.get_channel(904216460010872832)
        if not message.author.bot:
          async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
            if entry.created_at.now() == datetime.datetime.now():
                ModDeleted = True
          embed = discord.Embed(title="Message Deleted By Mod")
          embed.add_field(name="Member: ", value = message.author.mention, inline=True)
          embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
          embed.add_field(name = "Message: ", value = message.content, inline=False)
          embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)

          await channel.send(embed=embed)
        if ModDeleted == False:

          embed = discord.Embed(title="Message Deleted")
          embed.add_field(name="Member: ", value=message.author.mention, inline=False)
          embed.add_field(name="Message: ", value=message.content, inline=True)
          embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)

          await channel.send(embed=embed)
#

u need to define who is ModDeleted here

slate swan
#

is this how you do it i forgot how

member = discord.Member
echo wasp
slate swan
stiff nexus
#

member:discord.Member

slate swan
dense swallow
stiff nexus
#

1st you need to check whether the user has mod perms or not

echo wasp
#

lol

stiff nexus
#

exactly

#

there are many ways lol

#

u check there perms/roles

echo wasp
dense swallow
#

U can use the decorator

#

@commands.has_perms

echo wasp
dense swallow
#

U want the bot to say "you can't use that cmd" if the user does not have perms?

stiff nexus
dense swallow
#

It limits the cmd

stiff nexus
#

ya

dense swallow
#

Yeah

stiff nexus
#

but he is doing a event lol

dense swallow
#

Just make a separate error handler

stiff nexus
#

that u can

devout iris
#

How can i set ping command as embed?

stiff nexus
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

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

bool(b) Returns whether the embed has any data set.

New in version 2.0.

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/master/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.
echo wasp
devout iris
#

@stiff nexus i did embed but i have a few errors

devout iris
#

i dont wanna see ' and (

dense swallow
#

Code?

devout iris
#

A sec

dense swallow
echo wasp
#

I do mine like this or like thispy embed=discord.Embed(title='How long it took', description=f'The command took {time.time()-t:02.02f} seconds to run!', color=0x1f8b4c)

embed = discord.Embed(title="Message Deleted")
              embed.add_field(name="Member: ", value=message.author.mention, inline=False)
              embed.add_field(name="Message: ", value=message.content, inline=True)
              embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)```
devout iris
echo wasp
# dense swallow I don't understand what ur trying to do

here go to #help-orange

@client.event
async def on_message_delete(message):
        channel = client.get_channel(904216460010872832)
        if not message.author.bot:
          async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
            entry.created_at.now() == datetime.datetime.now()
            if ModDeleted = True Then:
                embed = discord.Embed(title="Message Deleted By Mod")
                embed.add_field(name="Member: ", value = message.author.mention, inline=True)
                embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
                embed.add_field(name = "Message: ", value = message.content, inline=False)
                embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)

                await channel.send(embed=embed)
            else:

              embed = discord.Embed(title="Message Deleted")
              embed.add_field(name="Member: ", value=message.author.mention, inline=False)
              embed.add_field(name="Message: ", value=message.content, inline=True)
              embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)

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

it is a log event

devout iris
stiff nexus
devout iris
dense swallow
# devout iris
@bot.command()
async def ping(ctx):
    em = discord.Embed(description=f"{round(bot.latency*1000)}ms")
    await ctx.send(embed=em)
devout iris
#

ty i'm trying

echo wasp
#

@dense swallow so what do i do then

#

or @stiff nexus seems you both know how

devout iris
#

Ty it is working

upbeat otter
#

guys, why isnt this working?

@client.command()
async def rename(ctx, name):
  try:
    await client.user.edit(name=name)
  except Exception as e:
    print(e)

dense swallow
dense swallow
upbeat otter
manic wing
#

I think you need password or some shit

stiff nexus
upbeat otter
echo wasp
dense swallow
#

Try it, dk if it works... It requires password or smth like caeden said

upbeat otter
#

thank youu

devout iris
#

How can i find color codes?

dense swallow
#

Hex color codes?

devout iris
#

No, hex codes aren't working in embed i guess.

dense swallow
#

They will work

devout iris
dense swallow
#

Yeah

#

color=discord.Color.color_name

echo wasp
#

didn't add anymore imports for it

#

@devout iris

dense swallow
#

U can do this

em = discord.Embed(color=discord.Color.blue()) # for blue color
echo wasp
#

so i took a different apporch to it

#

ok idc

devout iris
#

Thx

dense swallow
#

Np 👍

manic wing
#

How do you do timestamps with the bot?

slate swan
manic wing
#

There are no more updates

#

Feel free to fork and play around w/ it

boreal ravine
zinc reef
#

you mean like <t:123123123:R> ?

devout iris
#

how can i make it error when a normal user uses this command??

kindred epoch
devout iris
#

Should i debug?

#

try:
except funcs?

kindred epoch
#

?

#

i said it sends an error already

#

do you not know what handle means

devout iris
#

No

#

my brain has dead rn

slate swan
#

@client.event
async def on_ready():
print("==================")
print("Logged in as")
print('{}'.format(client.user.name))
print("{}".format(client.user.id))
print("==================")
print('Servers connected to:')
for guild in client.guilds:
print(guild.name)
print(guild.id)
print(guild.members)
print("==================")

How would I go about making this print how many members are in a server as a number?

#

Guild.members lists each member individually

slate swan
#

Basic Python

#

How would I implement that?

#

Literally wrote it

#

guild.members returns a list, get it's length with len()

#

If you don't know how to do that, consider learning Python

#

And consider using f-strings

#

Discord.py is not supposed to be for beginners as stated multiple times in the documentation

#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

Will help you to start learning Python

visual yarrow
#

!warn 897958982159859742 Let's not use homophobic slurs in this server please.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied warning to @slate swan.

slate swan
#

Thanks ^^

#

Weird

visual yarrow
#

@slate swan Please try not to engage in gate-keeping behaviour. This pinned message explains it better than I can: #discord-bots message

echo wasp
#

thank you so much I didn't know how to do that I had the member welcome not adding roles so I just modified it to fit my bot parameters and it worked I didn't just copy and paste it i worte it on how i needed it and i only needed half

echo wasp
#

why isn't this working? it worked at 12:00 pst time now it doesn't messed around with it because it did half ```py
ModDeleted=commands.has_permissions(manage_messages=True)
Not_ModDeleted=commands.has_permissions(manage_messages=False)

@client.event
async def on_message_delete(message):
channel = client.get_channel(904216460010872832)
if not message.author.bot:
async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
entry.created_at.now() == datetime.datetime.now()
if ModDeleted:
embed = discord.Embed(title="Message Deleted By Mod")
embed.add_field(name="Member: ", value = message.author.mention, inline=True)
embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
embed.add_field(name = "Message: ", value = message.content, inline=False)
embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)

            await channel.send(embed=embed)
        if Not_ModDeleted:

          embed = discord.Embed(title="Message Deleted")
          embed.add_field(name="Member: ", value=message.author.mention, inline=False)
          embed.add_field(name="Message: ", value=message.content, inline=True)
          embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)

          await channel.send(embed=embed)```
kindred epoch
echo wasp
kindred epoch
#

🤷‍♂️

kindred epoch
#

wdym find the error

#

ur supposed to tell me the error

echo wasp
kindred epoch
#

The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage.

dapper cobalt
#

Not if ModDeleted because you're simply not specifying which user you are trying to know if they have the permissions or not.

slate swan
#

How would I go about making a command that can be run in one server that does something in another? For example if I typed !say (channel or guild ID) (message) it would say it in a different server?

kindred epoch
kindred epoch
#

!d discord.TextChannel.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

huh

worn crow
kindred epoch
#

guild has dms now?

echo wasp
dapper cobalt
worn crow
#

is it in docs

#

and if so please link docs

kindred epoch
dapper cobalt
worn crow
slate swan
#

Like I have an old server that I can’t make an announcement in anymore due to losing perms cos new account but I have an old bot in there and I want to be able to make it dm everyone in that server to send our new server

worn crow
dapper cobalt
#

I know.

slate swan
#

Would there be a somewhat easy way to make it so I can just use a command to dm users of that server specifically and not any others the bots in

worn crow
slate swan
kindred epoch
#

@slate swan but ur inactive on this acc

slate swan
#

How would I do it externally

slate swan
worn crow
#

i think you can create webhook using bot then send to that webhook

echo wasp
worn crow
echo wasp
worn crow
#

to run bot commands

worn crow
slate swan
#

This just turned into nothing helpful aha

#

But thanks I guess 🙂

echo wasp
worn crow
slate swan
#

I’ll figure it out eventually will just be way to much code for something that will probably be real simple

worn crow
#

bruh my dumb internet

echo wasp
worn crow
worn crow
slate swan
#

Completely off it, I have the guild ID, want to dm the members in that server a message explaining what happened with a command like !say (guild id) (message) in a different server.

#

Hopefully that’s a bit of a better explanation

echo wasp
#

hmm

#

wait

slate swan
#

I have the actual command just need a way to use guild id in it

#

I’ll send in a second

echo wasp
#

i have an idea

#

so i have experimented

echo wasp
#

and got one thing happen in one it logs in another

#

and that was on event

#

or command'

slate swan
#
@client.command()
async def alert(ctx, *, message):
    for user in list(ctx.guild.members):
        try:
            await asyncio.sleep(0.5)    
            await user.send(message)
            await ctx.send(f'Sent "{message}" To {user}')
        except:
            pass```
#

That works but only where the command is run

echo wasp
#

so if you have server id then you can run the command from another server

slate swan
#

Yes

echo wasp
#

or channel id

kindred epoch
worn crow
slate swan
echo wasp
slate swan
#

I need to run it externally

echo wasp
#

i got it

worn crow
#

yesss

echo wasp
#

let me make it

worn crow
#

kk

echo wasp
#

do you have a channel id?

worn crow
#

my idea is webhooks

slate swan
#

Not a channel ID no

echo wasp
#

can you get a list of channels with id's or not possible

#

@worn crow

slate swan
#

I would be able to

#

But I don’t think it’s to necessary

#

As I should only need the guild ID right?

echo wasp
#

it if you want to use it externally

kindred epoch
slate swan
#

Exactly

#

The ctx.send sent message should prolly be print as well

worn crow
echo wasp
#

hmm

slate swan
#

I need to dm them not send something in a channel

echo wasp
#

do you have a server id

worn crow
slate swan
worn crow
echo wasp
#

may I have it

worn crow
slate swan
#

I don’t see why you need it

#

773795551845154816

echo wasp
slate swan
#

Ok

worn crow
worn crow
kindred epoch
worn crow
echo wasp
slate swan
#

No

worn crow
kindred epoch
slate swan
#

Webhooks are not what I need anyway

worn crow
#

thats why i make one for every server i have

kindred epoch
#

@slate swan use get_guild and then iterate over it and then send the message to all the users in that guild

worn crow
#

just incase

slate swan
kindred epoch
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
echo wasp
# slate swan No

try this

async def alert(ctx, *, message):
    for user in list(773795551845154816):
        try:
            await asyncio.sleep(0.5)    
            await user.send(message)
            await ctx.send(f'Sent "{message}" To {user}')
        except:
            pass```
manic wing
#

this is why you use syntax.

echo wasp
#

I found that out

kindred epoch
slate swan
#

This server is cooked

worn crow
slate swan
#

Normally helpful lmao

worn crow
slate swan
#

Somehow managed to find people more incompetent

kindred epoch
unkempt canyonBOT
slate swan
#

Thanks

kindred epoch
#

use that to get a guild obj from the id and then iterate over the members from it and use .send to send the message

#

!d discord.User.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

good luck

slim whale
#
  if guild.partnered == True:
    partner = "![partner](https://cdn.discordapp.com/emojis/895324925143949362.webp?size=128 "partner")"
  else:
    partner = ""
  if guild.verified == True:
    verified = "![Verified](https://cdn.discordapp.com/emojis/904839071468232734.webp?size=128 "Verified")"
  else:
    verified = ""``` want to check if the server is partnered or verified and put the badge of the server, but guild.partnered isn't correct and guild.verified too
#

how it would be?

kindred epoch
#

thats guild.features

#

not guild.partnered

#

guild.features returns a list, check if partnered and verified is in that list

slim whale
#

ohhh

#

thanksss

echo wasp
echo wasp
regal ferry
#

how can i delete all roles with one command? i am trying in my own server but i don't know how

worn crow
worn crow
worn crow
slate swan
#

how i can i send a regular message and embed in the same message? e.g i want it to @ the user before the embed

slate swan
slate swan
#

whats the thing that makes your text to python

regal ferry
slate swan
#

yw

slate swan
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

thx

#

np

#
import discord
import json
import os
from discord.ext import commands, tasks


class xp(commands.Cog):


    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        with open("users.json", "r") as f:
            users = json.load(f)

            await update_data(users, member)

            with open("users.json", "w") as f:
                json.dump(users, f)

    @commands.Cog.listener()
    async def on_message(self, message):
        with open("users.json", "r") as f:
            users = json.load(f)

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message.channel)

        with open("users.json", "w") as f:
            json.dump(users, f)
            await bot.process_commands(message)

    async def update_data(self, users, user):
        if not user.id in users:
            users[user.id] = {}
            users[user.id]["experience"] = 0
            users[user.id]["level"] = 1

    async def add_experience(self, users, user, exp):
        users[user.id]["experience"] += exp

    async def level_up(self, users, user, channel):
        experience = users[user.id]["experience"]
        lvl_start = users[user.id]["level"]
        lvl_end = int(experience ** (1/4))

        if lvl_start < lvl_end:
            await bot.send_message(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
            users[user.id]["level"] = lvl_end

def setup(client):
    client.add_cog(xp(client))
#

On line 28 theres an error, name 'update_data' is not defined

#

bot.send_message is no longer a thing

#

I don't know hy

#

Use channel.send

worn crow
slate swan
kindred epoch
#

"lucas used it"

#

no wonder

worn crow
slate swan
slate swan
kindred epoch
worn crow
kindred epoch
#

WHAT?

slate swan
slate swan
kindred epoch
slate swan
#

^^

worn crow
worn crow
echo wasp
slate swan
kindred epoch
#

wtf is fatabase

worn crow
slate swan
kindred epoch
#

😂

slate swan
worn crow
#

hey who here using replit to host discord bots

kindred epoch
kindred epoch
worn crow
slate swan
#

lol

worn crow
worn crow
slate swan
#

still a lot better from my experience with both

worn crow
#

and its so confusing

slate swan
#

¯_(ツ)_/¯

echo wasp
# kindred epoch python or heroku?

yes if they are using json why not python instead this a python server and host it on HEROKU i do and it doesn't lag or i can't notice how do i setup a command to get a time count?

worn crow
#

ok gn

slate swan
#

gn

echo wasp
slate swan
#

json != javascript just so you know

slate swan
echo wasp
echo wasp
slim whale
#

@kindred epoch

worn crow
#

i cant sleep

slim whale
#
@bot.command()
async def features(ctx):
  guild = ctx.guild
  await ctx.send(f"{guild.features}")```how i can make that if that contents partnered or verified it puts a emoji? @kindred epoch
echo wasp
#

how do you setup a proper ping command? i just have pong command

slate swan
#

@echo wasp json is just a file system, you can use it to store data in the form of a "dict", python is a coding language, they're 2 completely different things, and heroku is a host provider

#
import discord
import json
import os
from discord.ext import commands, tasks


class xp(commands.Cog):


    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        with open("users.json", "r") as f:
            users = json.load(f)

            await self.update_data(users, member)

            with open("users.json", "w") as f:
                json.dump(users, f)

    @commands.Cog.listener()
    async def on_message(self, message):
        with open("users.json", "r") as f:
            users = json.load(f)

        await self.update_data(users, message.author)
        await self.add_experience(users, message.author, 5)
        await self.level_up(users, message.author, message.channel)

        with open("users.json", "w") as f:
            json.dump(users, f)

    async def update_data(self, users, user):
        if not user.id in users:
            users[user.id] = {}
            users[user.id]["experience"] = 0
            users[user.id]["level"] = 1

    async def add_experience(self, users, user, exp):
        users[user.id]["experience"] += exp

    async def level_up(self, users, user, channel):
        experience = users[user.id]["experience"]
        lvl_start = users[user.id]["level"]
        lvl_end = int(experience ** (1/4))

        if lvl_start < lvl_end:
            await channel.send(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
            users[user.id]["level"] = lvl_end

def setup(client):
    client.add_cog(xp(client))
``` **I've added the selfs, but now the xp doesn't update + it doesn't give an error so Idk wat im ment to do**
slate swan
kindred epoch
slate swan
regal ferry
#

@slate swan may i ask you another thing

slate swan
#

?

echo wasp
#

how do you setup a proper ping command? i just have pong command like to tell how long the react time is

slate swan
unkempt canyonBOT
#

property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
slate swan
#

^^

#

Returns in seconds if I remember correctly

#

yea

kindred epoch
left wind
#

how do i send a message with buttons

regal ferry
#

ok so basically, if the bot tries to delete an integration role (like his own role) it gives an error and the loop stops, how can i make it not happen? i probably need a try: and except: thing right?

slate swan
kindred epoch
slate swan
slate swan
echo wasp
#

so how do i set it up? don't know the property family very well

kindred epoch
slate swan
#

Nothing to set up

#

Just get the value from your bot variable

slate swan
#

Get bot.latency then multiply by 1000 since you probably want the ping in ms

slate swan
#

btw this code is stolen from stackover flow i didnt make it

slate swan
kindred epoch
# slate swan where?
await channel.send(channel, f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!")
echo wasp
slate swan
#

!f-strings

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.

slate swan
# left wind how do i make a view 😅
import discord

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="Click Me")
    async def my_button(self, button: discord.Button, interaction: discord.Interaction):
        await inter.response.edit_message("Thanks for clicking me!", ephemeral=True)

# Somewhere in a command:
await ctx.send('Hello', view=MyView())
slate swan
kindred epoch
echo wasp
left wind
slate swan
echo wasp
slate swan
#

Yup

#

Now you can just round it to an integer with int()

#

Then it will be an integer instead of a float

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

slim whale
#

tnx

slate swan
#

You should take a look at learning Python before doing bots and projects

echo wasp
slate swan
#

No

#

In the () you put the bot.latency*1000

echo wasp
slate swan
#

It basically converts what's inside the () to an integer

#

Same for str(), float(), etc.

kindred epoch
#

@echo wasp do you know python?

echo wasp
kindred epoch
#

huh?

#

yes, its exactly what u typed

slate swan
#
@client.command()
async def send(ctx, guildid, *, message):
  for guild in client.guilds:
    guild = client.get_guild(guildid)
    members = (guild.members)
    for members in guild.members:
        try:
            await asyncio.sleep(0.5)    
            await members.send(message)
            await ctx.send(f'Sent "{message}" To {members}')
        except:
            pass```

So I have figured out server by server command but now it keeps saying object has no attribute “members” on the `    members = (guild.members)` line
regal ferry
#

how can you check if a role is deletable or not?

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
#

Fixed sorry

#

Why do you do a for loop to later overwrite all the time the guild variable?

#

guild will always be the same, you can delete your for loop

kindred epoch
slim whale
#

https://www.w3schools.com/python/python_conditions.asp can u use this to learn python @kindred epoch ?

slate swan
#

Should I use member or user instead?

slim whale
kindred epoch
#

why do you need 2 *

#

ok?

#
  • is used to get all the text after the arg its put after
#

i said all the text not 1 thing

wary forge
#

c++ the best

kindred epoch
#

ok and?

#

it is

#

what

#

send the error

#

ah ik

#

use get_channel

#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.
void mortar
#

bc the bot not in that guild?

kindred epoch
#

guild has no attribute channel, thats why its not working

onyx skiff
#

someone can help me to add roles on a member in my server with a command mention in the tchat

kindred epoch
#

thats why use discord.Guild.get_channel to get a channel obj from a certain guild and then use .send on it

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @void mortar until <t:1635804489:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 125 newlines in 10s).

onyx skiff
rain apex
#

!unmute 386179923364151307

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @void mortar.

rain apex
#

!paste please

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

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

onyx skiff
#

"Damné" is the name of my role in my serv

kindred epoch
# onyx skiff

add_roles takes a role obj not a str, use get_role to get a role object using the id

onyx skiff
#

@bot.command()
@commands.has_permissions(administrator=True)
async def addrole(ctx, role : discord.Role, member : discord.Member):
pseudo = member.mention
await member.add_roles("Damné")
await ctx.send(f"le role a correctement été donné à {pseudo}")

kindred epoch
#

put it before the .send, then use the id the members used in the brackets so something like this:

guild = bot.get_guild(guildid)
channel = guild.get_channel(channelid)
await channel.send("hi")
onyx skiff
#

@kindred epoch isn't working

#

i have the same answer in the console

kindred epoch
#

what do you think

onyx skiff
#

just the part of my script addrole ?

kindred epoch
#

what?

onyx skiff
kindred epoch
#

arent u adding the guild id and the channel id in the command tho?

#

and then that?

onyx skiff
#

"Damné" is the name of my role i resay

kindred epoch
onyx skiff
#

@kindred epoch xd

#

@kindred epoch i'm sexy and i know it

kindred epoch
#

?

#

then take it from that?

#

common sense?

#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
kindred epoch
#

click on the title and read what it does

kindred epoch
#

holy shit im not going to spoonfeed u

void mortar
#

no it was the result of print(*dir(discord.Guild), sep='\n') xd

onyx skiff
#

@kindred epoch i tried an other way to my code but isn't running i'll whow u

kindred epoch
#

and i asked u to read what get_guild does

#

@onyx skiff please learn more python before using a not beginner friendly library.

manic wing
#

you having fun here? xD

kindred epoch
#

is the bot in that guild?

onyx skiff
#

@kindred epoch i'm a got on python you d'ont know that and i have the lmfao attribute

kindred epoch
#

ur a got on python?

#

and i d'ont

#

and u have the lmfao atribute?

onyx skiff
#

@kindred epoch better of u

#

absolutely

kindred epoch
#

@forest lion can you send the error

onyx skiff
#

@kindred epoch you don't know that I live in PAris and I am in the family of Emmanuel Macron

#

and I eat bread and croissant every mornings

kindred epoch
#

nice to know

#

actually, can you try changing guild and channel attributes to int, and then try it

manic wing
#

you can’t typehint to discord.Guild afaik

onyx skiff
#

@kindred epoch I visit the eiffel tower with the lmfao attribute

onyx skiff
#

@kindred epoch are you jealous a little bit ?

kindred epoch
#

why would i

onyx skiff
#

because I've the lmfao attribute and not u

kindred epoch
#

ok

onyx skiff
#

@kindred epoch say a french word to e please I like the strange people

unkempt canyonBOT
onyx skiff
#

!va te faire enculer @kindred epoch

kindred epoch
#

change discord.Guild and discord.TextChannel to int

onyx skiff
#

baguete baguette

#

oui baguette

kindred epoch
onyx skiff
#

search on gg trad

#

between french to english

echo wasp
#

@kindred epoch help please

kindred epoch
echo wasp
#

it was working fine until i added the Case sensitive

kindred epoch
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

its right there

echo wasp
#

I used my own command is it because i am going insensivtive?

kindred epoch
kindred epoch
#

then add it lmfao

#

help command is a default command

echo wasp
#

oh how

kindred epoch
echo wasp
kindred epoch
#

add help_command=None

echo wasp
kindred epoch
#

show where you addded that

echo wasp
#

in that

kindred epoch
echo wasp
kindred epoch
#

did you save and restart the bot?

echo wasp
#

and it auto saves

#

i use vs code

kindred epoch
#

ok then idk

echo wasp
#

so do what then email discord lol

#

yes

#

he just helped me

#

just ping him

#

can you show code

kindred epoch
#

channel is none

echo wasp
#

@kindred epoch it run just fine when i removed ```py
, case_insensitive=True

echo wasp
kindred epoch
#

yep

echo wasp
kindred epoch
echo wasp
#

that is where i had it

kindred epoch
echo wasp
kindred epoch
echo wasp
kindred epoch
#

what

#

help_command=None

echo wasp
#

well poop

kindred epoch
#
@bot.command()#6600 ##Usage: grid!send <serverid> <channelid> This is a test message
async def send(ctx,guild: int,channel: int,*,message):
    guild = bot.get_guild(guild.id)
    channel = guild.get_channel(channel.id)
    await channel.send(f"{message}")
``` @forest lion try this
pale zenith
#

that code is fucked up lol

kindred epoch
#

wait remove .id

pale zenith
#
@bot.command()
async def send(ctx, channel: int, *,message):
    channel = bot.get_channel(channel)
    if channel:
        await channel.send(f"{message}")
slate swan
#

i was about to say

#

bpt? lol

echo wasp
#
client=commands.Bot(command_prefix='%', intents=intents, Help_command=None, case_insensitive=True)```
blissful lagoon
#

please dont use ableist language

slate swan
#

why remove the help command? it looks nice

pale zenith
#

sorry

echo wasp
#

and my file won't work

slate swan
#

oh, alright

echo wasp
#

so my bot won't launch

slate swan
#

it looks nice tho- at least i thought

echo wasp
slate swan
#

ah, ok

echo wasp
#

so can you help with my error

pale zenith
#

which is?

echo wasp
#

it still is broken i stumped him

pale zenith
#

did help_command=None not fix that?

#

🤔

echo wasp
pale zenith
#

try bot.remove_command('help')

echo wasp
#

n

pale zenith
#

of course its up to you

pale zenith
#

before you define your help right?

#

well your command is named Help not help

echo wasp
#

yes so when i do case insensitive i get a not launching even though i disabled that

#

top one

#

it works when i do this

#

just not when i do this

pale zenith
echo wasp
pale zenith
#

actually

#

client.remove_command

#

idk if this may be causing issues. Probably

#

bot=client

echo wasp
pale zenith
#

what?

#

i mean if your bot is named client, then use client lol

echo wasp
#

it worked great thanks

pale zenith
#

np!

echo wasp
#

see you did right

pale zenith
#

o

#

client.remove_command('help') will work the same

echo wasp
#

ok

#

now for the test

echo wasp
pale zenith
#

np

echo wasp
#

Help this only works half can someone expain why? It just does it when the bots delete the message not if a user deletes them

@client.event
async def on_message_delete(message):
        channel = client.get_channel(904216460010872832)
        if not message.author.bot:
          async for entry in message.guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
            entry.created_at.now() == datetime.datetime.now()
            if entry.user.guild_permissions.manage_messages:
                embed = discord.Embed(title="Message Deleted By Mod")
                embed.add_field(name="Member: ", value = message.author.mention, inline=True)
                embed.add_field(name = "Mod: ", value = entry.user.mention, inline=True)
                embed.add_field(name = "Message: ", value = message.content, inline=False)
                embed.add_field(name = "Channel: ", value = message.channel.mention, inline=False)

                await channel.send(embed=embed)
            else:

              embed = discord.Embed(title="Message Deleted")
              embed.add_field(name="Member: ", value=message.author.mention, inline=False)
              embed.add_field(name="Message: ", value=message.content, inline=True)
              embed.add_field(name="Channel: ", value=message.channel.mention, inline=False)

              await channel.send(embed=embed)```
merry pewter
#

Share, Script Python Invite

#

Not I Want to Make a Script Like Invite Tracker

void mortar
slate swan
#

how do I import pycord

languid lagoon
#

Hello guys, been a while since I've done some discord bot coding. And would like to ask whats a good replacement for discord.py, since it was discontinued a while back.

languid lagoon
slate swan
#

and there's no other changes from dpy yet I assume?

stark ingot
echo wasp
stark ingot
#

Please ping with a response

languid lagoon
stark hearth
stark ingot
#

both look very even to me
pycord has about 2 times as many stars on github and a more offical looking support discord but it looks like nextcord is trying to be good as well.

#

Another thing in the d.py discord i looked at servers that the online nitro boosters were in, about half of the 15 were in pycord hlaf were not in either and 1 person was in nextcord (they were also in pycord tho.)

#

I think I am going to go with pycord for now

outer violet
#

i watched this video on sqlite3 https://youtu.be/Y9DzfPJsP2s but i dont really understand it- my bot is in a couple of test servers and when someone joins one of the test servers, it sends a message to my server saying this message even though they never joined mine, so im just trying to make that stop

import discord
from discord.ext import commands

class Test(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_member_join(self, member):
        guild = self.client.get_guild(781422576660250634)
        channel = self.client.get_channel(816799996279652393)
        await channel.send(f"You made it {member.mention}! Welcome to **{guild.name}**, enjoy your stay 💚")

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

My discord server ► https://discord.gg/sfYjTSA
(If you have any questions or just want to have a chat with us)

(Some Cool Stuff)
Nertivia ► https://nertivia.supertiger.tk/
My server in Nertivia ► https://nertivia.supertiger.tk/invites/B4tMwO

Install discord.py ► pip install discord.py or py -3 pip install discord.py
Discord.py documentation ►...

▶ Play video
stark ingot
#

yes?

kindred epoch
#

Lol

#

Is that more important or the features it provides?

#

Imo I would go with disnake which already supports slash commands,context menus and apps

#

Its easy and stable

#

Great support team and already has an external lib which supports d.py also

#

And the only reason pycord has more stars than anyone is because of the owner having a big yt Channel and an already existing big discord server

#

I mean I'm not here to stop u, you can use pycord but Im just telling that there's better libraries out there which supports more features than the one which has more stars or is more famous

stark ingot
#

Ok, I will consider it

languid lagoon
#

oh, so options are Pycord, nextcord, and disnake..

mortal dove
#

I need some help. For some reason, my bot is not responding to any commands. It starts up fine and loads cogs and whatnot, but it just doesn't register any commands. I already reset my key, any other ideas?

mortal dove
#

Yes

#

I already checked wether it was running somewhere else

#

online/offline correspond to me turning the code on/off

languid lagoon
#

yep. btw, has it worked before? like have you added something and it didn't work?

mortal dove
#

ye it has worked for months now, I haven't changed much except deleted a cog that wasn't being used.

#

I can't think of any reason why that was cause the flux, though.

kindred epoch
#

Where are you hosting it

mortal dove
#

Flask, not sure about the details though

#

a friend did that stuff

kindred epoch
#

Hm

languid lagoon
#

not sure but I think flask is a library. Where do you start and stop it?

#

is it locally on a command line? or do you connect to a vps or another server?

mortal dove
#

I have a local bot.py file that sets up cogs, flask server, and all that jazz, and a local bot_config file that handles imports and such

#

Nothing in that area has been changed.

kindred epoch
#

Maybe the channel that ur using has perms for the bot not to talk

mortal dove
#

I use a permission plugin for dev tools

#

shows send_messages as True, and the channel has no requirements

#

Well I have it as Admin is True, nothing else

kindred epoch
#

Uh no idea, try opening a support ticket

mortal dove
#

Alr, if anyone else knows lmk please

mortal dove
kindred epoch
#

Ye

#

Discord support shit idk

languid lagoon
#

all I could think, is that maybe when you deleted some stuff, there was some indentation error or brackets that were left open. but if thats the case, it would return an error

mortal dove
#

Yeah, no errors

#

this is what it returns, if helpful at all

#

OHP i have idea that may solve

#

I also turned on message content intents a bit before bot went fizz.

#

dang still nothing

trim fulcrum
#
@commands.command(aliases=['avatar'])
    async def avatar(self, ctx, member : discord.Member = None):
        """
        Get the current avatar of your user!
        """
        if member is None:
            embed = discord.Embed(title="This command is used like this: 
            await ctx.send(embed=embed)
            return

        else:
            embed2 = discord.Embed(title=f"{member}'s Avatar!", colour=0x0000ff, timestamp=ctx.message.created_at)
            embed2.add_field(name="Animated?", value=member.is_avatar_animated())
            embed2.set_image(url=member.avatar_url)
            await ctx.send(embed=embed2)``` error

``` Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\Desktop\Kaneki-Main\bot.py", line 139, in on_command_error
    raise error
discord.ext.commands.errors.CommandNotFound: Command "avatar" is not found```
slate swan
#

anybody have ideas for some commands?

mortal dove
slate swan
halcyon folio
mortal dove
#

OH yeah that's it, good catch lol.

trim fulcrum
mortal dove
#

Do other commands in the same class work?@trim fulcrum

trim fulcrum
#
ExtensionFailed: Extension 'cogs.general' raised an error: CommandRegistrationError: The alias avatar is already an existing command or alias.```
mortal dove
#

...just check if anything else is named that or has that alias

mortal dove
#

Apparently there is, did you reload your cog/save code?

kindred epoch
trim fulcrum
pale zenith
#

there's no reason for the error to lie to you

mortal dove
#

ah

silent ermine
halcyon folio
#

probably have an on_message somwhere without process_commands

#

or message intent but i doubt it

calm vortex
#

I was about to say that

mortal dove
#

I mean there's quite a lot of it

#

@silent ermine

#

I don't think discord would like 6.4 MB of code

silent ermine
silent ermine
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

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

calm vortex
#

I want to point out that

@bot.command()
async def restart(ctx):
  app = await bot.application_info()
  if ctx.author in app.team.members:
    await ctx.send('Restarting...')
    print('Restarting...')
    await bot.logout()
    await bot.login(os.environ['token'])

is bad.

The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().

Do use:

  • run your bot in a process manager such as:
    • systemd
    • openrc (gentoo, devuan)
    • runit (void linux)
    • supervisord
    • upstart (old ubuntu)
    • docker
  • manually reboot it

Do not use:

  • a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
  • subprocess.call (you will eat your memory up by not letting your old processes die)
  • os.exec*
trim fulcrum
#

Kaneki Support has [<Member id=771095966060773407 name='Kaneki Bot' discriminator='5317' bot=True nick=None guild=<Guild id=895832701129601034 name='Kaneki Support' shard_id=None chunked=False member_count=106>>] in it!

@commands.command(aliases=["members"])
    async def membercount(self, ctx):
        guild = ctx.guild
        await ctx.send(f'{guild.name} has {guild.members} in it!')```
#

why did i get that message

mortal dove
#

Ok, but that doesn't fix the issue.

mortal dove
trim fulcrum
mortal dove
#

use len(guild.members)

trim fulcrum
#

ight

calm vortex
trim fulcrum
#

{len(guild.members)}

mortal dove
#

yeah

trim fulcrum
#

?

#

ok

calm vortex
#

Otherwise you will get just 1

fleet axle
#
async def button(ctx):
    await ctx.send("Click below Button", components=[Button(label="Button Testing", custom_id="button1")])
    interaction = await client.wait_for(
        "button_click", check=lambda inter: inter.custom_id == "button1"
    )
    await ctx.interaction.send("Button Clicked")```
#

this is my button code

#

and it says interaction failed

#

any help

slate swan
#

error in your console?

fleet axle
#

no

#

no error

slate swan
#

or discord-components smthing

fleet axle
fleet axle
slate swan
fleet axle
#

okay

#

I will try

slate swan
#

it takes a type kwarg too

fleet axle
#

no respond

slate swan
#

you would be using type = InteractionType.ChannelMessageWithSource

#

or just type=4

fleet axle
#

channel message with source is 4 right

slate swan
#

ye

fleet axle
#

yass

gaunt herald
#

How can i make mute command ?

slate swan
#

1 , setting up a mute role for the server with send message perms off in all channels ( either manual or using bot)
2 , get the role
3 . add the role to the user

gaunt herald
#

but I need to do it on every server my bot in?

brave vessel
fleet axle
#

@slate swancan u once send me whole code with type

slate swan
slate swan
fleet axle
#

okay thanks

#

nope still says interaction failed

gaunt herald
#

ok

slate swan
#

also , do you have an error handler?

fleet axle
#

no errors

slate swan
zenith basin
#
@bot.command()
async def addxp(message, amount, user: commands.Greedy[discord.Member]):
    members = user or message.author
    for j in range(0, len(members)):

        cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)",
                                      (message.guild.id, members[j].id, 1))

    if cursor.rowcount == 0:
        print(len(members), members)
        for j in range(0, len(members)):
            print(members[j].id)
            await bot.db.execute(
                f"UPDATE guildData SET exp = exp {str(amount[0])} {str(amount[1:])} WHERE guild_id = ? AND user_id = ?",
                (message.guild.id, members[j].id))

        cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
                                   (message.guild.id, message.author.id))
        data = await cur.fetchone()

        exp = data[0]
        lvl = math.sqrt(exp) / bot.multiplier

        if lvl.is_integer():
            for k in range(0, len(members)):
                member = members[k].id
                for i in range(len(level)):
                    if lvl == levelnum[i]:
                        await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
                        embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
                        embed.set_thumbnail(url=member.avatar_url)
                        await message.channel.send(embed=embed)
    await bot.db.commit()


@bot.command()
async def xp(ctx, user: discord.User = None):
    member = user or ctx.author

    # get user exp
    async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
                              (ctx.guild.id, member.id)) as cursor:
        data = await cursor.fetchone()
        exp = data[0]

        # calculate rank
    async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id)) as cursor:
        rank = 1
        async for value in cursor:
            if exp < value[0]:
                rank += 1

    lvl = math.sqrt(exp) // bot.multiplier

    current_lvl_exp = (bot.multiplier * (lvl)) ** 2
    next_lvl_exp = (bot.multiplier * ((lvl + 1))) ** 2

    lvl_percentage = ((exp - current_lvl_exp) / (next_lvl_exp - current_lvl_exp)) * 100

    embed = discord.Embed(title=f"Stats for {member}", colour=discord.Colour.gold())
    embed.add_field(name="Level", value=str(int(lvl)))
    embed.add_field(name="Exp", value=f"{exp}/{int(next_lvl_exp)}")
    embed.set_thumbnail(url=ctx.author.avatar_url)

    embed.add_field(name="Level Progress", value=f"{round(lvl_percentage, 2)}%")

    await ctx.send(embed=embed)
#
Ignoring exception in command xp:
Traceback (most recent call last):
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\wolf\Observant Force discord\main.py", line 77, in xp
    async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id)) as cursor:
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\context.py", line 41, in __aenter__
    self._obj = await self._coro
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 184, in execute
    cursor = await self._execute(self._conn.execute, sql, parameters)
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
ValueError: parameters are of unsupported type

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type
cursive barn
#

Aiosqlite it seems

slate swan
#

the paramaters to enter must be a tuple

zenith basin
slate swan
#

( data1 , data2 , data3 ,)

#

with a extra comma at last

zenith basin
cursive barn
zenith basin
#

using Type()

slate swan
zenith basin
#

@slate swan my problem is in addexp cmd

#
 if lvl.is_integer():
            for k in range(0, len(members)):
                member = members[k].id
                for i in range(len(level)):
                    if lvl == levelnum[i]:
                        await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
                        embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
                        embed.set_thumbnail(url=member.avatar_url)
                        await message.channel.send(embed=embed)
slate swan
zenith basin
slate swan
zenith basin
#

now wrks thx

slate swan
#

cool

zenith basin
#

@slate swan Thanks for helping but do you have time I have one more question rq

zenith basin
#
Ignoring exception in command addxp:
Traceback (most recent call last):
  File "C:\Users\wolf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\wolf\Observant Force discord\main.py", line 60, in addxp
    await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
AttributeError: 'int' object has no attribute 'add_roles'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ZIV\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ZIV\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\ZIV\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'add_roles'
2 [<Member id=555944200047296513 name='Ꮤøℓƒ' discriminator='0001' bot=False nick=None guild=<Guild id=825821295307915304 name='test' shard_id=None chunked=True member_count=6>>, <Member id=840315621073223703 name='AnimeManSad' discriminator='1457' bot=False nick="Wolf's alt" guild=<Guild id=825821295307915304 name='test' shard_id=None chunked=True member_count=6>>]
555944200047296513
840315621073223703
#
async def addxp(message, amount, user: commands.Greedy[discord.Member]):
    members = user or message.author
    for j in range(0, len(members)):

        cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)",
                                      (message.guild.id, members[j].id, 1,))

    if cursor.rowcount == 0:
        print(len(members), members)
        for j in range(0, len(members)):
            print(members[j].id)
            await bot.db.execute(
                f"UPDATE guildData SET exp = exp {str(amount[0])} {str(amount[1:])} WHERE guild_id = ? AND user_id = ?",
                (message.guild.id, members[j].id,))

        cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?",
                                   (message.guild.id, message.author.id,))
        data = await cur.fetchone()

        exp = data[0]
        lvl = math.sqrt(exp) / bot.multiplier

        if lvl.is_integer():
            for k in range(0, len(members)):

                for i in range(len(level)):
                    member = members[k].id
                    if lvl == levelnum[i]:
                        await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
                        embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
                        embed.set_thumbnail(url=member.avatar_url)
                        await message.channel.send(embed=embed)
    await bot.db.commit()
#
        if lvl.is_integer():
            for k in range(0, len(members)):

                for i in range(len(level)):
                    member = members[k].id
                    if lvl == levelnum[i]:
                        await member.add_roles(discord.utils.get(member.guild.roles, name=level[i]))
                        embed = discord.Embed(description=f"{member.mention}. New role: **{level[i]}**!!!")
                        embed.set_thumbnail(url=member.avatar_url)
                        await message.channel.send(embed=embed)
#

@slate swan this code above what giving me problems ^^^

#

Ꮤøℓƒ#0001

#

@zenith basin

slate swan
#

guys how can we make slash commands in python
exclude discord.py

#

guys how can we make slash commands in python
exclude discord.py

slate swan
#

ok

slim linden
#

how to check if there is any type of ping in a message

slate swan
#

message.mentions

slim linden
#

ok

slate swan
#

like if```
message.mentions in message.content:
#then the action

slim linden
#

Thanks!

slate swan
#

try this

#

if not working

#

dm me\

#

for basic ness

#

u can use if '@' in message.content:

#

It's

for mention in message.mentions:
    print(mention) # This is the user that got mentioned
print(len(message.mentions)) # The number of mentioned users in the message, will be 0 if nobody got mentioned
halcyon folio
zenith basin
#

has anyone here used the roblox api if so dm me?

#

has anyone here used the roblox api if so pls help me.

slate swan
#

sc = SlashCommand(bot, sync_commands=True)

#

If I sent an attachment, the message.content will be None right?

halcyon folio
#

no

#

depends

merry pewter
#

Pls Share Script Invite Tracker

boreal ravine
#

Eye sore?

strong kettle
#

Hi ,

How can i get page name in googleserach library?

jade tartan
#

Hi i have this code where i would want to put the emoji in an embed and also let it react to to the embed so that the user can get a role with that reaction

#
async def embed(ctx, get):
    emoji = get(ctx.message.server.emojis, name="Male"),
    emoji = get(ctx.message.server.emojis, name="Female"),
    Myembed = Embed(title= f"Please pick your gender role by reacting to the emoji", color=0x24045b,
    description=f"Gender role")
    await client.say(embed=Myembed)
#
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'get' is not defined```
#

hang on nvm i think i know the soluton

#

nvm

dense swallow
jade tartan
dense swallow
#

how did u import?

jade tartan
#
from discord import FFmpegPCMAudio
import os
from discord.ext import commands
import discord.utils
from discord.utils import get
import datetime
from datetime import datetime
import json```

```import discord.utils
from discord.utils import get```
dense swallow
#

Imported 2 times?

dense swallow
jade tartan
#

ohh i thought once u have import discord.utils you then from there u import get

#

mb

dense swallow
#

async def embed(ctx, get):

jade tartan
#

it said get wasnt defined but it should work without it since i imported get

dense swallow
#

Yes

jade tartan
#

import discord.utils import get is it import get or from?

#

cuz it says invalid syntax