#discord-bots

1 messages · Page 570 of 1

brave vessel
#

You wouldn't need to break it as you want to go through each guild.

brave vessel
#

So, it seems like BOT_TOKEN is not in the current program. Do you have it defined somewhere, do you pull it from anywhere (.env)?

brave vessel
echo wasp
brave vessel
# echo wasp

You indented twice, you want to only indent once to keep consistency and you also want to put the print code inside the for loop and also remove the if guild.name == GUILD

magic stump
brave vessel
#

Like this:

    for guild in client.guilds:
        print(guild.name)
        print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})\n'
        )
    
        members = '\n - '.join([member.name for member in guild.members])
        print(f'Guild Members:\n - {members}')
slate swan
#

he simply has to put the print in the if statement

echo wasp
#

and got it fixed

slate swan
#

oh wait the if statement is just dumb

#

then k

magic stump
brave vessel
#

Hm, did you pull it from the env?

#

How did you get the bot token

slate swan
#
@av.error
async def avatar(ctx, error,member : discord.Member = None):
    if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
        msg = await ctx.send(embed = discord.Embed(title = 'Invalid Response',description = f"Error: There is no such user, {ctx.message.author.mention} please try again.", color = 0x5865f2))
        embed.set_footer(text="Thank you for using Cursex")
        ctx.embed.timestamp = datetime.utcnow()
        await asyncio.sleep(7)
        await msg.delete()
        await ctx.message.delete()
magic stump
slate swan
#

the footer won't load

brave vessel
magic stump
#

env

#

BOT_TOKEN = {asd2jsdfajj2eskas}

brave vessel
#

Usually with os.environ and python-dotenv

This should help:
https://vcokltfre.dev/tips/tokens/

magic stump
#

?

#

aijw

brave vessel
lyric moat
#

how can i make first message command?

brave vessel
#

You seem a bit confused about for loops in general though, do you have any questions about them?

echo wasp
brave vessel
#

So, say I have a list with the words "apples", "oranges", and "bananas"

#

!e

my_list = ["apples", "oranges", "bananas"]

for fruit in my_list:
  print(fruit)
unkempt canyonBOT
#

@brave vessel :white_check_mark: Your eval job has completed with return code 0.

001 | apples
002 | oranges
003 | bananas
brave vessel
#

The fruit part of this is the variable that Python will bind each element to

slate swan
#
@av.error
async def av(ctx, error,member : discord.Member = None):
    if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
        msg = (await ctx.send(embed = discord.Embed(title = '',description = f"`Error: There is no such user,` {ctx.message.author.mention} `please try again.`", color = 0x2f3136)
        embed.set_footer(text="error your mom")))
        await asyncio.sleep(1)
        await msg.delete()
        await ctx.message.delete()

error:

  File "C:\Users\User\Desktop\bot discord server console — копия\bot.py", line 159
    embed.set_footer(text="error your mom")))
    ^
SyntaxError: invalid syntax
Press any key to continue . . .
#

opened 1 bracket, closed 3

#

don't work why not

slate swan
#

yes

#

msg = await ctx.send(embed = discord.Embed(title = '',description = f"Error: There is no such user, {ctx.message.author.mention} please try again.", color = 0x2f3136))

#

this would work

#

and remove two ) of the set_footer

undone wyvern
#

No it wouldn't lol

#

Nvm

slate swan
#

...

undone wyvern
#

On mobile it's formatted so poorly that I didn't see the first bit

slate swan
slate swan
undone wyvern
#

Wym

#

Is the footer not deleted when you delete the message?

slate swan
#

it is not deleted at all

kindred epoch
#

does not even need it

brave vessel
echo wasp
slate swan
# undone wyvern Is the footer not deleted when you delete the message?

error:

  File "C:\Users\User\Desktop\bot discord server console — копия\bot.py", line 159
    embed.set_footer(text="error your mom"))
    ^
SyntaxError: invalid syntax
Press any key to continue . . .

code:

@av.error
async def av(ctx, error,member : discord.Member = None):
    if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
        msg = await ctx.send(embed = discord.Embed(title = '',description = f"`Error: There is no such user,` {ctx.message.author.mention} `please try again.`", color = 0x2f3136)
        embed.set_footer(text="error your mom"))
        await asyncio.sleep(1)
        await msg.delete()
        await ctx.message.delete()

kindred epoch
placid skiff
#

how can I use converters if i don't have a context?

kindred epoch
slate swan
#

it's all in "msg"

kindred epoch
#

im loosing brain cells rn

placid skiff
#

lol

kindred epoch
slate swan
#

-_-

kindred epoch
#

and you dont even need to put it in "msg"

placid skiff
slate swan
kindred epoch
#

?

slate swan
#

. . .

placid skiff
kindred epoch
#

do you know how attributes work?

slate swan
#

sure

kindred epoch
#

doesn't look like it

placid skiff
#

!d discord.ext.commands.Context.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**.
placid skiff
#

delete_after deletes the message after n seconds

#

there is a way to use converters without passing a context?

slate swan
#

or call the function directly

#

discord.Embed().set_footer()

slate swan
coral vessel
#

How to set bot sending photos from my computer using this

@bot.event
async def on_message(message):
if message.content == "Ping":
await message.channel.send('Pong')

is that possible ?

#

i know @bot.command can perform send photos but how about this one ?

kindred epoch
coral vessel
kindred epoch
hollow palm
#
msg = await ctx.channel.send(f"`Now playing: {var3}` \n{url}")
await msg.add_reaction(u"\u23F8")
await msg.add_reaction(u"\u25B6")
try:
    reaction, user = await client.wait_for("reaction_add", check=lambda reaction, user: reaction.emoji in [u"\u23F8", u"\u25B6"], timeout=90.0)

except asyncio.TimeoutError:
    return await msg.clear_reactions()

else:
    if reaction.emoji == u"\u23F8":
        await msg.remove_reaction(reaction.emoji, ctx.author)
        await ctx.voice_client.pause()
    elif reaction.emoji == u"\u25B6":
        await msg.remove_reaction(reaction.emoji, ctx.author)
        await ctx.voice_client.resume()

This code is supposed send a message showing what is playing, and bring up pause and play reactions which will pause and play the audio when reacted to by a user. Right now it only works the first time the command is called, after that any new times the command is called the reactions do not do anything, additionally, it only responds to a reaction once, for example if someone hits the pause emoji then the audio will be paused, however if the play emoji is hit after that then nothing will happen.

slate swan
supple thorn
kindred epoch
hollow palm
#

but how much would i loop the for loop?

kindred epoch
#

what

#

put it right above the wait_for

#

so after its finised it will go straight back to the wait_for

#

wait

hollow palm
#

Yes I understand, but wouldn't it be better to use a while loop because it would be an undefined amount of times that it would have to repeat

kindred epoch
#

im wrong

#

yea thats what i mean LMFAO

#

i mixed it up

hollow palm
#

Ok but what would I put as the condition?

kindred epoch
#
while True:
    #wait_for stuff
hollow palm
slate swan
#
@client.command()
  async def beg(ctx):
    people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
    amount = random.randit(1, 1000)
    title = random.random(people)
``` if im correct this should have no errors right?
echo wasp
#

why doesn't this work I have checked around and it should work fine```py
@client.event
async def on_member_remove(member):
channel = client.get_channel(904073508269731860)
embed=discord.Embed(title=f"{member.name} Left", description=f" {member.name}has left{member.guild.name} sad to see you go :( ")
embed.set_thumbnail(url=member.avatar_url)

await channel.send(embed=embed)``` this works fine for the join message

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

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

and i'm pretty sure it's on_member_remove, not on_member_leave

slate swan
#
@client.command()
  async def beg(ctx):
    people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
    amount = random.randint(1, 1000)
    title = random.random(people)
    embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
    await ctx.reply(embed=embed)
    db2.update_one({"user": ctx.author.id},
    {"$push": {"bal": amount}})
#

wtf is wrongf

#

nvm

#

nvm i found what was wrong, the db wont update

#

how can I do this?

#

embed.footer

#

!d discord.Embed.footer

unkempt canyonBOT
#

property footer: _EmbedFooterProxy```
Returns an `EmbedProxy` denoting the footer contents.

See [`set_footer()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.set_footer "discord.Embed.set_footer") for possible values you can access.

If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
slate swan
#

icon_url=

slate swan
#
@client.command()
  async def beg(ctx):
    people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
    amount = random.randint(1, 1000)
    title = random.choice(people)
    embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
    await ctx.reply(embed=embed)
    db2.update_one({"user": ctx.author.id},
    {"$set": {"bal": amount}})
``` how can i add there before value to there after value
#
@client.command()
  async def beg(ctx):
    people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
    amount = random.randint(1, 1000)
    title = random.choice(people)
    embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
    a = db.find_one({"user": ctx.author.id})["bal"]
    new_value = f"{a}+{amount}"
    r = eval(new_value)
    await ctx.reply(embed=embed)
    db2.update_one({"user": ctx.author.id},
    {"$set": {"bal": r}})
``` new stuff
#

what do yu mean

echo wasp
slate swan
#

set a channel for each server

echo wasp
#

how do i add it in

slate swan
#

i would prefer using a database

#

recommend *

echo wasp
#

so i just want it to do 2-3 servers but idk how to add them in

kindred epoch
#

They already answered you

slate swan
#

@kindred epoch ur smart can u help me

#
@client.command()
  async def beg(ctx):
    people = ["Bill Gates", "Mom", "Dad", "Steve Jobs", "Votcy"]
    amount = random.randint(1, 1000)
    title = random.choice(people)
    embed = discord.Embed(title=f"{title}",description=f"{title} just gave you **⏣ {amount}**",color=0x2f3136)
    a = db.find_one({"user": ctx.author.id})["bal"]
    new_value = f"{a}+{amount}"
    r = eval(new_value)
    await ctx.reply(embed=embed)
    db2.update_one({"user": ctx.author.id},
    {"$set": {"bal": r}})
``` new stuff
kindred epoch
#

What do you need help with

slate swan
#

Create variable doesn't return url what to do to get url

kindred epoch
#

Huh?

slate swan
#

how do i check if a member has nitro?

slate swan
pliant gulch
#

Discord doesn't give any reliable way to check if a user has nitro

echo wasp
#

what things should my bot do? so far it does 3 commands 2 text back 1 does something

rain olive
echo wasp
slate swan
#

Hello! To handle invalid token errors, I use this:

bot = Roover()
  token = os.getenv('TOKEN')
  try: 
    bot.run(token, reconnect=True)
  except Exception as a:
    handler(a).efilter()```

However still get this error:


    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
rain olive
echo wasp
rain olive
echo wasp
rain olive
#

otherwise youre going to have a really hard time

echo wasp
#

I learn on the way

rain olive
#

it's not a beginner friendly library, you'll be fustrated at many errors

slate swan
#
@client.command()
  async def serverinfo(ctx):
    server_created = ctx.server.created_at.strftime("%d %b %Y %H:%M")
    embed = discord.Embed(description=f"Server | {ctx.guild.name}\nID | {ctx.guild.id}\nCreated At | {server_created}\nOwner | {ctx.guild.owner}\nMembers | {ctx.guild.member_count}\nRoles | {len(ctx.guild.roles)}\nChannels | {len(ctx.guild.channels)}\nText Channels | {len(ctx.guild.text_channels)})\nVoice Channels | {len(ctx.guild.voice_channels)}\nBoosts | {ctx.guild.premium_subscription_count}")
    embed.set_footer(text=f"Invoked By: {ctx.author}",icon_url=ctx.author.avatar_url)
    embed.set_thumbnail(url=ctx.guild.icon_url)
    await ctx.reply(embed=embed)
``` i dontt even know what the error is
#

its not returnign anything in terrminal

rain olive
slate swan
#

Does it send? If not then do you have an on_message event by any chance?

slate swan
#

dont send and no

#

Did you save and restart

#

mhm

#

ill restart one more time

#

You could try adding prints everywhere and see where it stops printing

slate swan
rain olive
#

@slate swan this is a useful debugging tool, simply do pip install jishaku and add this to ur main.py then do !jsk dbg (your_command)

client.load_extension("jishaku")
slate swan
unkempt canyonBOT
rain olive
#

it comes in handy when there are no terminal errors

slate swan
#

should i run this in a public channel?

rain olive
#

anywhere

#

this will make ur bot DM you the error that didnt show in ur terminal

slate swan
#

it did nothing

rain olive
#

wdym nothing, how did u debug it?

#

show the command

slate swan
#

!jsk dbg serverinfo

#

thats what i did

rain olive
#

did it react on ur command?

slate swan
#

no, do i need to use the correct prefix?

#

Yes

rain olive
#

yes 😭

slate swan
#

omg you said "!" so i thought to use that

rain olive
#

replace ! with ur own prefix

slate swan
#

LOL

rain olive
#

i thought it was understood but nvm, do it again

#

react on the trashbin while ure at it

slate swan
#

omg i put server instead of guild

rain olive
#

there we goo

slate swan
#

dumbest error, but thank you that is actually so useful

#

and i had no clue that even existed

rain olive
#

now you do :)

echo wasp
rain olive
#

not all errors you can google and fix

echo wasp
rain olive
#

note your use of language, most

echo wasp
slate swan
#

most of the code on google/stack is outdated and is making simple things complicated

rain olive
#

from my experience only the simple things you can find on stack overflow, when you encounter bugs in classes etc you likely wont find a solution

echo wasp
slate swan
#

So your just gonna skid code..

rain olive
#

I mean lets be honest if the solutions can be found on stack overflow whats the need of all these channels here...

slate swan
#

fr, or if you could just look anything up and it will work

rain olive
#

For more complicated code you'll need others' assistance and quite a fair bit of Py knowledge

slate swan
#

why dont they make server an alias of guild

rain olive
#

ask Danny

slate swan
#

oh i forgot they discontinuted

slate swan
rain olive
slate swan
#

people are used to calling it servers though

#

yeah

#

getting used to guild is kinda aids

#

the word server would mean many other things in coding tho

#

^

#

hmm good point

pliant gulch
#

It used to be server but later changed to guild

#

I'd assume because that's the correct discord terminology

trim fulcrum
#
@commands.command(name="serverinfo")
    async def serverinfo(self, context):
        """
        Get some useful (or not) information about the server.
        """
        server = context.message.guild
        roles = [x.name for x in server.roles]
        role_length = len(roles)
        if role_length > 50:
            roles = roles[:50]
            roles.append(f">>>> Displaying[50/{len(roles)}] Roles")
        roles = ", ".join(roles)
        channels = len(server.channels)
        time = str(server.created_at)
        time = time.split(" ")
        time = time[0]

        embed = discord.Embed(
            title="**Server Name:**",
            description=f"{server}",
            color=0x42F56C
        )
        embed.set_thumbnail(
            url=server.icon_url
        )
        embed.add_field(
            name="Owner",
            value=f"{server.owner}\n{server.owner_id}"
        )
        embed.add_field(
            name="Server ID",
            value=server.id
        )
        embed.add_field(
            name="Member Count",
            value=server.member_count
        )
        embed.add_field(
            name="Text/Voice Channels",
            value=f"{channels}"
        )
        embed.add_field(
            name=f"Roles ({role_length})",
            value=roles
        )
        embed.set_footer(
            text=f"Created at: {time}"
        )
        await context.send(embed=embed)```
#

error

#
File "C:\Users\user\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\user\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\user\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: AttributeError: 'NoneType' object has no attribute 'id'```
#

ping me when answer

rain olive
rain olive
#

slap the ticks

trim fulcrum
#

i cant

#

its a verified bot

rain olive
#

since ure bot is verified u'll need to request for it

slate swan
#

hello

#

Is anyone alive here?

maiden fable
#

Nah

boreal ravine
boreal ravine
slate swan
#
                if message.author.permissions.manage_messages:
                    return

is this proper?

boreal ravine
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
boreal ravine
slate swan
#
@client.command()
async def welcome(ctx, user:discord.Member=None):
    if ctx.author.guild_permissions.manage_messages:
        if user is None:
            await ctx.reply("Woah, how can you think of welcoming no one?")
        elif user.bot:
            await ctx.reply("Sorry but bots don't care even if you welcome them...")
        elif user==ctx.author:
            await ctx.reply("You cannot welcome yourself!")
        elif user.top_role >= ctx.author.top_role:
            await ctx.reply("Bruh, you cannot welcome someone who is already in such a high rank!")
        else:
            visitor_role=ctx.guild.get_role(698500675306258452)
            if visitor_role in user.roles:
                try:
                    await user.remove_roles(visitor_role)
                    initiate_role=ctx.guild.get_role(698500328169013258)
                    await user.add_roles(initiate_role)
                    try:
                        await user.send_message(f'You are not a member of {ctx.guild.name}!')
                    except Exception:
                        pass
                    await ctx.message.delete()
                    await ctx.channel.send(welcomemsg.replace("(userhere)", f"{user.mention}"))
                except Exception:
                    await ctx.reply("Missing permissions for that user")
            else:
                await ctx.reply("User doesn't have visitor role")```

IDK why but it show indentation error in await `ctx.message.delete()`
boreal ravine
#

what does dik mean

slate swan
boreal ravine
#

that isnt a question mark question

#

😮‍💨

slate swan
#

@client.command() async def welcome(ctx, user:discord.Member=None): if ctx.author.guild_permissions.manage_messages: if user is None: await ctx.reply("Woah, how can you think of welcoming no one?") elif user.bot: await ctx.reply("Sorry but bots don't care even if you welcome them...") elif user==ctx.author: await ctx.reply("You cannot welcome yourself!") elif user.top_role >= ctx.author.top_role: await ctx.reply("Bruh, you cannot welcome someone who is already in such a high rank!") else: visitor_role=ctx.guild.get_role(698500675306258452) if visitor_role in user.roles: try: await user.remove_roles(visitor_role) initiate_role=ctx.guild.get_role(698500328169013258) await user.add_roles(initiate_role) try: await user.send_message(f'You are not a member of {ctx.guild.name}!') except Exception: pass await ctx.message.delete() await ctx.channel.send(welcomemsg.replace("(userhere)", f"{user.mention}")) except Exception: await ctx.reply("Missing permissions for that user") else: await ctx.reply("User doesn't have visitor role")

slate swan
#

WHY DOES IT GIVE ME ERROS

slate swan
boreal ravine
#

stop copying code

#

bruh

viral nymph
#

i need help

boreal ravine
#

I'll help later busy atm

slate swan
boreal ravine
#

¯_(ツ)_/¯

slate swan
#

ok

#

<@&267630620367257601>

viral nymph
#

my goal is to make a discord bot that will tell me if someone is online in a minecraft server, for exemple :

online (mc name)
yes : (the name) is online !
no : (tne name) is not online !

#

using an account 24 / 7 inside the server

slate swan
#

can somone send me a code for a modmail?

boreal ravine
#

Don't ping helpers for this

slate swan
boreal ravine
#

You can fix the error by yourself

#

It's basic python knowledge

slate swan
#

lol I didnt pinged

boreal ravine
#

Doesn't matter

slate swan
#

I just did this to draw attention 😄

boreal ravine
#

oh attention seeker nice

#

go fix your error by yourself :/

boreal ravine
slate swan
#

Fixed 😄

#

😀

boreal ravine
#

ok?

slate swan
#

\👌

#

.

balmy nest
#

?membercoun t

#

?membercount

boreal ravine
#

#bot-commands please

spring flax
boreal ravine
#

thought it was pingable

#

considering the role is called helper

#

¯_(ツ)_/¯

slate swan
#
@client.command()
async def welcome(ctx, user:discord.Member=None):
    if ctx.author.guild_permissions.manage_messages:
        if user is None:
            await ctx.reply("Woah, how can you think of welcoming no one?", delete_after=4.0)
            await time.sleep(4)
            await ctx.message.delete()```
#

indentation error

boreal ravine
#

ur ide bugged xD

tough wagon
#

why this error appears?

slate swan
sullen shoal
slate swan
#

but fixed when I replaced all 4spaces with \t

sullen shoal
#

whats the ide

slate swan
#

I dont use ide

sullen shoal
#

bruh cmd?

slate swan
#

notepad++ and cmd

#

I use it

sullen shoal
#

so notepad++ is your ide

slate swan
#

you can say

waxen granite
#

Is there a way to disable a cog commands in a specific guild?

sullen shoal
#

cog check

pale zenith
#

the cog_check method of a cog class

#

!d discord.ext.commands.Cog.cog_check

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
waxen granite
#

I am trying to make a cmd to save the message and response when that msg is in message. How can i do it?

#

Like if there is a msg hello the bot to reply with hello sir.

slate swan
#

code

@client.event
async def on_message(message):
  find = collection.find({"_id": message.guild.id})
  for i in find:
    l = i['channel']['current'] + 1
    f = i['channel']['id']
    if message.channel.id == f:
      if message.content == l:
        await message.add_reaction('☑️')
      else:
        await message.delete()
        embed = nextcord.Embed(title='Counting', color = nextcord.Color.random())
        embed.description = "It seems you typed the wrong number. If this was done interntionally please stop it ruins the fun for others. If this was a mistake please make sure nobody else it typing a number so this doesn't happen again."
        await message.author.send()
    else:
      return

error

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 45, in on_message
    l = i['channel']['current'] + 1
TypeError: list indices must be integers or slices, not str
#
{"_id":{"$numberLong":"900936824803958834"},"channel":[{"name":"counting-channel","id":{"$numberLong":"904243700798984272"}}]}
#

the _id is the guild id

#

the id is the channel id

#

name is the channel name

#

and channel is a dictionary with those values in it

sullen shoal
#

!d discord.on_message

unkempt canyonBOT
#

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

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
wintry shore
waxen granite
sullen shoal
#

yes

slate swan
#

yeah ill be honest dont know what list indices

#

are

sullen shoal
hearty crest
#

is using io.bytesio in a discord bot good/fine?
and for how much time does it save the binary data in the memory?

wintry shore
slate swan
#

ok that makes sense

wintry shore
#

In a dict you use the key
but in a list theres no key so you use the item position

hearty crest
boreal ravine
#

!report

#

dont think you can 😂

heavy folio
#

#bot-commands ty

calm vortex
boreal ravine
heavy folio
#

so i just mentioned it

boreal ravine
#

ah ok

tough wagon
#

I want to make Tickets System, is there anything to know how it works?..

boreal ravine
#

on message

#

events

slate swan
#

I created cross server code do anyone test it

boreal ravine
#

whats cross server code

eternal ore
#

How can I edit/change a file from a message? something like this

message = await ctx.send(file=discord.File(...))
await message.edit(?=discord.File(...)) 

There is no file param

boreal ravine
#

you cant

eternal ore
#

I have seen discord bots do it

boreal ravine
#

Really

#

maybe because the images were in embeds

eternal ore
#

Yes, not written in python tho, and not in an embed

#

or maybe an embed

#

lemme check

boreal ravine
#

hm

eternal ore
#

oh yeah your right, it is an embed

boreal ravine
#

😂

eternal ore
#

then I know how to do it, thanks for pointing it out

boreal ravine
#

well bots can only do what users can do and users cant edit files in messages

#

👍

crude trellis
#

Hi

boreal ravine
#

show if self.guild.owner_id == member.id:

#

btw on_guild_remove gets triggered after the bot got removed from the guild

#

u cant send messages to it 😂

waxen granite
#

ah

#

it worked before

#

:c

tough wagon
rain olive
#

use buttons

#

upon a button click it shud create a channel such that mods and the person who created it can talk in it

tough wagon
#

hm ok

weary gale
#

when i put color=000000
it just comes up with an error

#

i cant set it to a specific color

#

help?

hazy fulcrum
#

On an on_message event, How do I extract the title from the embed from a different bot

hazy fulcrum
#

like if discord.embeds.title == 'Something'

weary gale
unkempt canyonBOT
weary gale
#

it just wont work for this one

tough wagon
tough wagon
weary gale
tough wagon
#

1st - use em.add_field and em.set_footer

#

2nd - so what isn't working? what error you get?

weary gale
#

whenever i use this

unkempt canyonBOT
tough wagon
weary gale
#

this happens @tough wagon

slate swan
boreal ravine
tough wagon
#

remove )() after color @weary gale

#

bruh

weary gale
#

i think i need to sleep more

tough wagon
#

and use em.add_field not like this

#

like this

rigid narwhal
#
# @has_permissions(manage_roles=True, manage_channels=True)
async def rename(ctx, *, text=''):
    if text == '':
        await ctx.send('.rename `oldname:newname` ')
    else:
        tag = text.split(';')[0].split(' - ')[0]
        oldname = text.split(';')[0]
        newname = text.split(';')[1]
        print(oldname)
        old_role = discord.utils.get(ctx.guild.roles, name=oldname)
        old_team_name = text.split(';')[0].split(' - ')[1]
        while old_team_name[0] == ' ':
            old_team_name = old_team_name[1:]
        old_Channel = f'{tag.lower()}-{old_team_name.lower().replace(" ", "-")}'
        print(old_Channel)
        old_channel = discord.utils.get(ctx.guild.text_channels, name=old_Channel)
        await old_role.edit(name=newname)
        await old_channel.edit(name=newname)
        await ctx.send('Done!')```

it says in error:

```Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

i am the owner of the server

weary gale
#

this fine?

tough wagon
#

no

weary gale
#

but i have to end the brackets

tough wagon
#

you create variable em
and on next lines use em.add_field

weary gale
#

ok

tough wagon
#

like py emb = Embed(...) emb.add_field(...)

weary gale
#

??

#

oh ok

weary gale
rigid narwhal
# tough wagon full traceback pls
  File "C:\Users\dell\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\dell\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\dell\AppData\Roaming\Python\Python39\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
tough wagon
# weary gale i specifically put anything in the brackets?

what is the question bruh?
learn py and read docs
ok i give you example

embed = discord.Embed(title="yes", description="no", color=discord.Color.blue())
embed.add_field(name="no", value="yes")
embed.add_field(name="ok", value="bruh", inline=False)```
tough wagon
rigid narwhal
#

ah okay thanks

tough wagon
#

manage channels maybe

#

or smth else

rigid narwhal
#

his role was beneath other roles, some admin fucked that up

#

thanks ❤️

boreal ravine
slate swan
#

in discord.VoiceClient.cleanup do you call disconnect in side it like this: VoiceClient.cleanup(await VoiceClient.disconnect)

maiden fable
#

Eh

#

@slate swan ???

#

There's nothing like clean up?

slate swan
#

!d discord.AudioSource.cleanup

unkempt canyonBOT
#

cleanup()```
Called when clean-up is needed to be done.

Useful for clearing buffer data or processes after it is done playing audio.
slate swan
#

hey

#

i have a problem with a database

#

the setup code is

boreal ravine
#

Whats the error/problem

slate swan
#
sync def setup():
    await client.wait_until_ready()
    client.db = await aiosqlite.connect("ekavData.db")
    await client.db.execute("CREATE TABLE IF NOT EXISTS money (money int, medkit int)")
    await client.db.execute("CREATE TABLE IF NOT EXISTS medkit (medkit int)")

    for guild in client.guilds:
        for invite in await guild.invites(): 
            await client.db.execute("INSERT OR IGNORE INTO money (money, medkit) VALUES (?,?,?)")
            await client.db.execute("INSERT OR IGNORE INTO medkit (medkit) VALUES (?,?,?,?,?)")
#

and the code is

#
@nextcord.ui.button(label="+1 Medkit", style=nextcord.ButtonStyle.green)
  async def Medkit1(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        await client.db.execute("INSERT INTO medkit (medkit)")
        await client.db.commit()
        await interaction.response.send_message(f'test', ephemeral=True)


  @nextcord.ui.button(label="-1 Medkit", style=nextcord.ButtonStyle.red)
  async def Medkit2(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        await client.db.execute("IGNORE INTO medkit (medkit)")
        await client.db.commit()
        await interaction.response.send_message(f'test', ephemeral=True)
#

i want it to make it when you click +1 medkit it add one in the database and when -1 medkit is clicked, it removes it

#

any ideas @boreal ravine ?

boreal ravine
#

well i have no experience with sql

slate swan
slate swan
#

Because you need to remove the parameters...

#

You just need to compare with the class without parameters

#

So just ...BotMissingPermissions

#

Then you can access with error.missing_perms the list of permissions missing

#
if isinstance(......):
    print(error.missing_perms) # will give list of permissions missing
#

But that's what you have to do

#

As you can't choose

#

Just make an if statement to check if the missing permissions list contains the send message permission

#

Come on, that's basic Python....

#

Then do it

slate swan
#

Sometimes you got to search and try things on your own

#

Not everything will be given one to one to you in life...

#
def drinks(user: discord.Member):
    db = sqlite3.connect("coin.sqlite")
    cursor = db.cursor()
    result = cursor.fetchrow(f"SELECT drink FROM coin WHERE member_id = {user.id}")
    
    
    if result[2] == None:
      sql = "INSERT INTO coin(drink) VALUES(?)"
      val = (1,)

    else:
    
      sql = "UPDATE coin SET drink = ? WHERE member_id = ?"
      val = (result[2]+1,user.id)
      
    db.execute(sql, val)
    db.commit()
    cursor.commit()
    a = cursor.execute("SELECT * FROM coin WHERE member_id = ?",(user.id,))
    print(a)
    cursor.close()
    db.close()```
#

my sql database is not getting updated

#

is my code right?

#

you aint commiting it in the last part

#

oh nvm , its just a select thingy

#

any errors tho?

elder meteor
#

question, which coding website is a good host for making my bot online every time? (ONES THAT ARE FREE AND WORK 24/7!)

undone wyvern
#

None

#

You literally won't find any free one that's good or even runs for 24/7

#

If you need it that bad you can buy a VPS for like $5 a month

slate swan
#

help me please

tawdry perch
floral jacinth
#

bot can send server's emoji on dm?

slate swan
#

sure

#

How i can do my bot 24/7 on?

floral jacinth
slate swan
unkempt canyonBOT
slate swan
#

pass the id in

#

lol

slate swan
floral jacinth
#

keep up 25 days every month

slate swan
#

Lol

#

It might work though

#

waits for a response

floral jacinth
#

buffering

floral jacinth
boreal ravine
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.

#

Hey @slate swan!

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

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

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

https://paste.pythondiscord.com

slate swan
#

?

#

read what it says

#

its a command for ban everyone

#

its correct?

#

mass banning is against tos , sir

#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

im sure you asked for "how to ban someone" and not how to ban everyone

slate swan
#

and who was that?

#

idk the name

#

well its not allowed so noone here would be providing that help

#

oh im sorry

boreal ravine
#

dyno does it

slate swan
boreal ravine
#

¯_(ツ)_/¯

boreal ravine
#

dyno does it??

slate swan
#

no

slate swan
undone wyvern
#

A lot of verified bots break ToS

slate swan
#

and this is obviously for raiding servers

undone wyvern
#

Dyno also has music so 🤷‍♀️

boreal ravine
slate swan
#

im aware that vortex bot has a ban command which can ban 'all the members mentioned' while using ban command

#

but not everyone

slate swan
boreal ravine
#

ban match.

#

@slate swan just use a for loop

undone wyvern
#

If you tried to ban everyone you would probably just get rate limited

slate swan
undone wyvern
#

You would need to have a sort of cooldown so that doesn't happen.

slate swan
undone wyvern
boreal ravine
#

it isnt lmfao

slate swan
#

use ubuntu , and feel me

boreal ravine
undone wyvern
#

I was going to say it could just be a beta feature but yeah

slate swan
#

Ubuntu KEKL

slate swan
#

Damn good thing I gotta go

boreal ravine
#

its common sense

undone wyvern
#

I know now...

slate swan
undone wyvern
#

What is wrong with people here now?

boreal ravine
#

just because something is not the right thing

slate swan
boreal ravine
#

doesnt mean its wrong

undone wyvern
#

It's fine though, let's just chill out and get back on topic :)

floral jacinth
boreal ravine
#

!d discord.ext.commands.Bot.get_emoji

unkempt canyonBOT
floral jacinth
slate swan
#

bot.get_emoji

undone wyvern
slate swan
#

your discord.ext.commands.Bot variable is bot

floral jacinth
slate swan
cinder horizon
slate swan
#

Nothing

boreal ravine
#

maybe its a secret slash kwarg

#

😱 😱

slate swan
#

Just put the id as parameter

cinder horizon
slate swan
slate swan
#

.get_emoji

undone wyvern
#

Lol

slate swan
#

imagine not having a __init__ in cogs

#

that's impossible

#

why?

undone wyvern
#

Can you even use cogs without the init?

floral jacinth
#

now Cannot send an empty message --_--

slate swan
#

I don't think so

#

.

slate swan
#

so it returns None

#

simple

floral jacinth
#

ye

boreal ravine
slate swan
floral jacinth
#

right click on emoji, copy id, done right?

boreal ravine
#

no

slate swan
#

in get_emoji

undone wyvern
#

In this case all you need is the ID

floral jacinth
#

⚠️

slate swan
floral jacinth
#

904326122114781194

undone wyvern
#

The bot probably just doesn't share a server with the emoji or something

boreal ravine
#

does it have emoji intents

slate swan
#

by default it does

boreal ravine
#

!d discord.Intents.emojis

unkempt canyonBOT
boreal ravine
#

hm

slate swan
#

( dont mind the ctx.respond)

floral jacinth
slate swan
boreal ravine
slate swan
boreal ravine
#

hm

slate swan
#

you can add a cog even with the main file

boreal ravine
#

a cog is subclassed

slate swan
#

it wont need a setup function tho , just bot.add_cog

craggy talon
floral jacinth
craggy talon
#

or commands?

boreal ravine
slate swan
floral jacinth
#

noone

slate swan
craggy talon
craggy talon
craggy talon
slate swan
#

?

floral jacinth
slate swan
boreal ravine
#

wait

slate swan
boreal ravine
#

its jsk oops

slate swan
#

ye

boreal ravine
#

no underscore more easier

slate swan
#

use
await ctx.send("<:emoji_47:904322924511641621:>")

floral jacinth
#

( i have no nitro)

slate swan
slate swan
boreal ravine
#

no underscore more easier opinions

floral jacinth
slate swan
#

is the bot in the server where the emoji is from?

floral jacinth
#

yes

slate swan
#

you sure that the id is correct ? how do you get it?

floral jacinth
#

right click, copy id

slate swan
#

nu thats the message id you get

#

use \:emoji: it will give the emoji id

#

paste that in get_emoji

devout iris
#

How can i set prefix as mention? i.e i want to ping bot and bot will say smthng

floral jacinth
#

\⚠️

slate swan
floral jacinth
#

i don't

slate swan
unkempt canyonBOT
#

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

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

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

try using with one in this server

floral jacinth
slate swan
#

command_prefix takes when_mentioned_or(prefix)

floral jacinth
#

ohw

slate swan
#

yea , now try that with your emoji

floral jacinth
slate swan
devout iris
slate swan
#

I would use on_message

#
if bot.user.mentioned_in(message):
    #do something
devout iris
#

Tysm!

gaunt mortar
#

Hi, someone know how I can make a graph like this in an embed message ?

boreal ravine
#

use a library for that

slate swan
#

that's probably an image?

boreal ravine
#

^

slate swan
#

okay

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/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
slate swan
#

then ask in a help channel and use the tag above

#

to set the image

gaunt mortar
slate swan
#

Some help here please

boreal ravine
undone wyvern
boreal ravine
#

!pypi matplotlib

unkempt canyonBOT
boreal ravine
#

that?

undone wyvern
#

Yeah that's not a bad one.

boreal ravine
slate swan
#

i do <clear 2 and it clears 2 messages but later the massage "Cleared 2 messages" gets not deleted

undone wyvern
#

Say the message after clearing

slate swan
#

my code

slate swan
#

u want see?

slate swan
#

you first delete the messages and then send another one, that's not gonna get deleted

zenith zinc
#

I first see this error pls help

slate swan
slate swan
slate swan
slate swan
#

he makes dpy tutorials, bad ones

slate swan
zenith zinc
slate swan
#

no, you pass in a delete_after keyword-argument @slate swan

boreal ravine
slate swan
zenith zinc
#

idk im just asking

slate swan
#

please not here

zenith zinc
#

k

slate swan
cursive vine
#

it’s not an f string

slate swan
#

oh

#

👍

#

btw you can add +1 to amount so the message which triggered the command gets deleted too

#

that would change many things

#

how and what?

#

I find this the absolute easiest way

slate swan
cursive vine
# slate swan oh

put an f before the first quotation mark or .format() with the right variable after the string

slate swan
slate swan
#

i have an biiiiiiiiiiiiiiiiiiiiiiig problem

#

how do my bot 24/7?

cursive vine
zenith zinc
zenith zinc
slate swan
zenith zinc
#

and see video

cursive vine
slate swan
cursive vine
slate swan
#

I personally didn't know Python either

cursive vine
#

Well you gotta start somewhere

slate swan
#

start at dpy be cool /s

#

yes

undone wyvern
#

Please don't.

slate swan
#

ducky_dave start with learning python in schools , and then miss school classes because you make bots on discord

#

y'all learn programming in school?

#

yes

cursive vine
#

and it’s not really programming tho

slate swan
#

i started learning py from class 9th , but thats too basic

#

oof

#

the things i learn now in class12th is not too high level either

#

grandpa

#

just some file handling and sql interactions

#

well those are useful things for sure

cursive vine
slate swan
#

not really hard, maybe the school isn't designed for that

#

yeah , i learned sql which i use in my bots there

cursive vine
#

we did microsoft office things in 9th grade lmao

#

1 entire year

#

using ms excel

slate swan
#

we too ,python was added just for practical things

#

earlier it used to be python for 9-10 and c++ for 11-12 ( its getting kind offtopic now lol)

wanton roost
#

Can I make whatever discord bot I want using python?

slate swan
#

but music bots or anything breaking ToS

wanton roost
#

wow like databse of cards and they should appear once in a while

cursive vine
slate swan
#

any ToS

cursive vine
slate swan
#

we can't help with music bots because of YouTube's one

#

for example

cursive vine
#

but you won’t be banned in Dc for music bots

#

especially not for small bots

wanton roost
#

like a discord bot for my playlists,I think im gonna make it

slate swan
#

well that's hard

#

good luck, unfortunately, we won't be able to help

wanton roost
#

whyy though, should i have playlist in youtube to make it

slate swan
#

!ytdl

unkempt canyonBOT
#

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

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

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

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

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

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

this would probably not be a problem if you ask youtube itself to give you permissions

#

and they agree, which they wouldn't

wanton roost
slate swan
#

How would I check if a user was mentioned in a command? For example, !kick @mention

#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
slate swan
#

And it kicks the user that was mentioned in the message

slate swan
slate swan
#

command

#

what do you have rn ?

#

@Commands.command

#

oh a cog?

#

@commands.command(pass_context = True)
@commands.has_role("Owner")
async def kick(ctx):

slate swan
#

just a simple command

#

did you define your bot object?

#

yes

#

should I send my whole code?

slate swan
slate swan
#

so , it will be py @botobject.command() @commands.has_role(....) async def kick(ctx , user : discord.Member):

commands.command is meant only to use in cogs
pass_context is no longer needed

#

oh yeah

boreal ravine
boreal ravine
#

you cant kick users objects

slate swan
#

my bad

boreal ravine
#

you can only kick member objects

slate swan
#

it would be a member

boreal ravine
#

👍

slate swan
#

@botobject.command()
@commands.has_role(....)
async def kick(ctx , user : discord.User):

#

when i try this

#

change .User to Member

#

the commands.has_role doesnt work

#

the role doesnt get found

#

uh , that was just for explanation

#

you need to add your botobject and role there

slate swan
slate swan
slate swan
inner pumice
#

quick question are banners changeable for bots

#

like to a certain photo

#

or does the owner need nitro or smth

boreal ravine
stable edge
steep estuary
#

how i can increase time by adding numbers ?

#

like time is 5:30

#

if i want to add 5000 seconds in it

#

then how i can get the time after 5000 seconds ?

slate swan
#

!d datetime.timedelta

unkempt canyonBOT
#

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

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
slate swan
#

add this to your datetime

normal ginkgo
#

Is there a way make a bot account and have a bot tag next to ur name? Im testing the discord API and I see u can actually do it

#

I know its against ToS, but imma do it for testing reasons

slate swan
#

a bot tag next to a normal user account?

normal ginkgo
#

Yeah

slate swan
#

even if one selfbots its not possible

normal ginkgo
#

Its part of the official API tho

#

Or was

slate swan
#

ofcourse , its just a explanation how the api works , discord already told it multiple times that automating a user account is against tos

normal ginkgo
#

Im not automating an account, I’m asking how to put the tag BOT next to ur name, its official in the API. Im doing this for api testing reasons.

slate swan
#

you cannot

normal ginkgo
#

Wasnt it part of the official API? I thought it was

slate swan
#

it never was

mortal dove
#

How difficult would it be to integrate slash commands into disocrd.py? Like is there any support at all?

dim wing
slate swan
#

yes

mortal dove
#

Yeah, it has all of the up-to-date things except slash commands

slate swan
#

but u can just use the beta

slate swan
mortal dove
#

Not sure

#

very well could be though

slate swan
#

2.0 includes everything but slash commands

ornate lichen
#

what are some godd meme api s i can use

#

for a discord bot

#

*good

manic wing
#

you need to defined client.sniped_messages as a dict first

slate swan
#

client.sniped_messages = {}?

icy mango
#

ig he copying code

#

right @slate swan what yu think

slate swan
#

yep

#

I've seen this code before

icy mango
#

@slate swan learn python bro it willl help you

icy mango
#

if you found an

ornate lichen
#

ok

icy mango
#

bruh

slate swan
#

Instead of asking here and making like you know the answer when replying to the user, you can directly tell them to come here... ¯\_(ツ)_/¯

boreal ravine
#

why not ask him instead of here?

slate swan
ornate lichen
#

yup

slate swan
#

Just use Reddit r/memes

#

And get a random meme from there

ornate lichen
#

how

boreal ravine
#

apis

slate swan
boreal ravine
#

hm

rare saddle
#

How to make sure that every time a ticket is created, its number changes? That is, 1 + 1 = 2 + 1 = 3 and so on.

slate swan
#

Create a counter

boreal ravine
#

how is this random?

icy mango
slate swan
#

These are the top/latest x memes posts, get a random one from there

boreal ravine
#

hm

slate swan
#

Not rocket science and basic Python knowledge lets you do that easily

ornate lichen
#

thanks:)

slate swan
#

So yes, you can make it random if you have enough knowledge

#

Which apparently you don't KEKL

slate swan
boreal ravine
#

how would I know how to make it random if I haven't even looked at the json yet? ¯\_(ツ)_/¯

slate swan
#

Then use your eyes, look at it, and only then say it's not random and make your comments 🤡

#

Judging before looking at it #typical

icy mango
#

how we use json

#

i dont know! maybe i can change it into txt and then split them with /n and then use random module will it work?

slate swan
icy mango
#

thanks

#

imma get a look at it

slate swan
#

But don't use the same method to request the URL

rare saddle
#

How to make sure that every time a ticket is created, its number changes? That is, 1 + 1 = 2 + 1 = 3 and so on.

slate swan
#

Basic Python

#

Create a counter per guild
Save it in a database or json if it's not big
Increment it every time after creating the ticket

rare saddle
slate swan
#

No need to send that lmao

rare saddle
slate swan
#

Well if you restart your bot it will start counting at 1 again

#

So maybe you want to save the counter of the guild, yes.

rare saddle
#

I know

slate swan
#

And if you don't care of that, just make a counter

rare saddle
#

How easy it is to add it every time

slate swan
#

It's python knowledge

rare saddle
#

I have not learned this yet

#

sorry

slate swan
#

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

Variables is the first thing you learn.

rare saddle
slate swan
#

You don't need that anyways

rare saddle
#

So how can you make a counter just using variables?

slate swan
#

!botvar

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!

slate swan
#

Create a bot variable and increment it when you create a ticket

rain ridge
#

what am i doing wrong? ```py
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="MUTED")
await member.remove_roles(member.roles)

if not mutedRole:
    mutedRole = await guild.create_role(name="MUTED")

    for channel in guild.channels:
        await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
embed = discord.Embed(title="muted", description=f"{member.mention} was muted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
await ctx.send(embed=embed)
await member.add_roles(mutedRole, reason=reason)
await member.send(f" you have been muted from: {guild.name} reason: {reason}")
boreal ravine
#

using copied code

rain ridge
#

is it a type of crime of smth?

spiral frigate
#

how to write deleted messages to the python discord variable.
For example: there are 2 messages and 1 command in the channel.
the bot is trying to clear 5 messages and output that it deleted 5 messages and there were 3 of them in total

boreal ravine
#

nope, just cant help you considering im on mobile

slate swan
#

What's your error

rain ridge
slate swan
#
x = ...purge()
len(x) # number of messages deleted
rain ridge
#

in remove_roles
await req(guild_id, user_id, role.id, reason=reason)

#

it cant remove roles

#

as it works without it

slate swan
#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / b
ZeroDivisionError: division by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

rain ridge
#
Traceback (most recent call last):
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/media/ranveer/New Volume/VS Code/Practice/Bot/bot.py", line 170, in mute
    await member.remove_roles(member.roles)
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/member.py", line 822, in remove_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'list' object has no attribute 'id'

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

Traceback (most recent call last):
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/ranveer/.local/lib/python3.8/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: 'list' object has no attribute 'id'```
slate swan
#

iterate thru the list

rain ridge
#

aight i'll try

slate swan
#
for role in member.roles:
  #remove it```
waxen granite
#
    async def removeserverstats(self, ctx):
        guild = ctx.guild.id
        for guild in self.serverstats.keys():
            await guild.pop()```
how can i remove the key here?
slate swan
#

is that a json , or a dictionary?

waxen granite
#

824359600584523876 and 695919805772988506 are keys

waxen granite
spiral frigate
# slate swan `.purge` returns the list of messages deleted, get it's length

how to do it here

    @commands.command(name= "очистить")
    async def clear(self, ctx, *, amount: Optional[int]) -> None:
        amount = amount or 0
        if amount == 0 or amount >= 101:
            embed = discord.Embed (
                title = 'Команда `s~очистить`',
                description = 'Команда `s~очистить` очистить какое-то количество сообщений \n в данном канале. Не забудь что я могу очистить 100 сообщений за раз, а также \n очень древние сообщения я не смогу удалить.',
                colour = 0x694c5f
            )
            embed.add_field(name= "Использование:", value= "> `s~очистить` `(Количество)`", inline= False)
            embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
            embed.add_field(name= "Пример:", value= ">>> `s~очистить` `100` \n ⮩ Очистит 100 сообщений", inline= False)

            await ctx.reply(embed = embed)
        else:
            await ctx.message.delete()
            await ctx.channel.purge(limit=amount)
            embed = discord.Embed (
                description = f':white_check_mark: Удаленно `{amount}` сообщений',
                colour = 0x694c5f
            )
            await ctx.send(embed = embed, delete_after= 3)
slate swan
slate swan
waxen granite
#

i am

#

says str obj has no att pop

slate swan
#

can you show the code

#

oh u did

slate swan
waxen granite
#

hm

spiral frigate
#

so

    @commands.command(name= "очистить")
    async def clear(self, ctx, *, amount: Optional[int]) -> None:
        amount = amount or 0
        if amount == 0 or amount >= 101:
            embed = discord.Embed (
                title = 'Команда `s~очистить`',
                description = 'Команда `s~очистить` очистить какое-то количество сообщений \n в данном канале. Не забудь что я могу очистить 100 сообщений за раз, а также \n очень древние сообщения я не смогу удалить.',
                colour = 0x694c5f
            )
            embed.add_field(name= "Использование:", value= "> `s~очистить` `(Количество)`", inline= False)
            embed.add_field(name= "Параметры:", value= ">>> <> - Необязательный параметр \n () - Обязательный параметр", inline= False)
            embed.add_field(name= "Пример:", value= ">>> `s~очистить` `100` \n ⮩ Очистит 100 сообщений", inline= False)

            await ctx.reply(embed = embed)
        else:
            await ctx.message.delete()
            await ctx.channel.purge(limit=amount)
            deleted = ...purge()
            len(deleted)
            embed = discord.Embed (
                description = f':white_check_mark: Удаленно `{amount}` сообщений',
                colour = 0x694c5f
            )
            await ctx.send(embed = embed, delete_after= 3)
slate swan
#

My guy

#

I shortened the code, don't copy paste what I've sent

icy mango
#
@client.command()
@commands.has_role(904013595208216598)
async def report_taken(ctx, message_id : int) :
    if message_id is None :
        await ctx.send("Syntax : er!report_taken <message_id>")
    
    else :
        help_log = client.get_channel(help_log_channel)
        report_message = await help_log.fetch_message(message_id)

        if report_message.author == client.user :
            if "Not Yet" in report_message.content :
                await report_message.reply(f"Report case taken by {ctx.message.author}")
                # await edit_message(message_id, f"Report Taken Staus : Taken by {ctx.message.author}")
                await report_message.edit(message_id, f"Report Taken Status : Taken by {ctx.message.author}")
            else :
                await report_message.reply("That is not my report message")
        
        else :
            await ctx.message.reply("That is not my message. Maybe you got the wrong message id?")
icy mango
# icy mango ```py @client.command() @commands.has_role(904013595208216598) async def report_...
Ignoring exception in command report_taken:
Traceback (most recent call last):
  File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\DELL\Desktop\The Epix Bot\main.py", line 235, in report_taken
    await report_message.edit(message_id, f"Report Taken Status : Taken by {ctx.message.author}")
  File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord_components\dpy_overrides.py", line 72, in edit
    data["embeds"] = [embed.to_dict()]
AttributeError: 'str' object has no attribute 'to_dict'

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

Traceback (most recent call last):
  File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\DELL\Desktop\The Epix Bot\env\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\DELL\Desktop\The Epix Bot\env\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: 'str' object has no attribute 'to_dict'

#

how i fix?

spiral frigate
lucid prism
#

how can i fix this ??

waxen granite
slate swan
#

!e py dict = { 'hm' : 34 } dict.pop('hm') print(dict)

icy mango
slate swan
slate swan
slate swan
unkempt canyonBOT
#

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

{}
lucid prism
icy mango
slate swan
icy mango
#

np

slate swan
#

hm

spiral frigate
slate swan
spiral frigate
#

I'm just Russian and I don't understand

slate swan
#
  • Add x= before where you used .purge()
  • Use len(x) to know how many messages got deleted
#

More than that I can't do

#

Aside from adding these 10-15 characters by myself in your code

#

Which is pretty much useless

waxen granite
slate swan
waxen granite
#

gives me key error

#

for the guild id

slate swan
#

what does the dict variable return?

#

could you show it

waxen granite
#

lemme print

boreal ravine
waxen granite
# slate swan could you show it

{'member_count': 891289849821298709, 'bot_count': 891289851108929546, 'text_count': 891289852631453766, 'voice_count': 891289853726191626, 'tier': 891289855018008596}

#

well it shouldnt have the [guild] part

slate swan
waxen granite
#

i tried before some error came.