#discord-bots

1 messages · Page 554 of 1

wary pollen
#

U messed up indenting

#

So, could u give code

#

@slate swan

#
# Importações

import discord
from discord.ext import commands

# Clasificação de classes

class Geral(commands.Cog):
    """Comandos gerais"""

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

    # Exemplo de comando:
    @commands.command()
    async def test(self, ctx):
    embed=discord.Embed(title="Meu Criador", description="Sr abelha#5441", color=0xffdd00)
    embed.set_author(name="Meu Criador")
    embed.add_field(name="Sr abelha#5441", value="Youtube: Sr abelha", inline=False)
    embed.set_footer(text="Bee Comunity")
    await ctx.send(embed=embed)        

def setup(bot):
    bot.add_cog(Geral(bot))```
slate swan
#

don't care about language

wary pollen
#

Ok

#

Could u point out which is line 16

#

@slate swan

#

Gtg sry

slate swan
#

I Have this, How do I tell the program to delete 7 day old logs?

#
@client.event
async def on_ready():
    date = datetime.datetime.utcnow().strftime('[%Y-%b-%d]')
    with open(f".\logs\{date}.txt", 'a') as f:
        f.write("\n" + f"{date} logs:" + "\n")
#

Ping me plz

#

not nearly related to dpy

#

help me

slate swan
slate swan
#

There are 2 people asking for help

#

answered both of them

wary pollen
#

After async

#

Add another indent

slate swan
#

Fix it for me and my mother is calling me to do homework

#

;--;

#

bruh

#

lost situation zarif

hasty iron
unkempt canyonBOT
#

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

This is equivalent to:

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

use that and compare it to utcnow() or now()

slate swan
#

mhm?

slate swan
#

forgot the "

#

after button.click

#

what's discord.components.client

#

isn't it discord_components

#

then why don't u use that

#

discord.ext.commands.Bot

#

what does that have to do with your current error

#

wait I just noticed

#

why are you calling event

#

there's no way the guy used @quaint axle.event() instead of @quaint axle.event

#

what error

#

you didn't finish the sentence

final pumice
#

what does context mean

slate swan
#

"discord.components.client" has no attribute

#

??

#

so then how did you define client

#

how did you use
client = ...

#

then you would get 'client' is not defined

#

just... how did you define client?

#

no, before the on_ready event

#

no, before that

#

!e

#string doesn't exist yet
print(mystring)
mystring = "Hello World!"
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | NameError: name 'mystring' is not defined
placid skiff
#

client = discord.ext.commands.bot(prefix = your_prefix)

slate swan
#

yeah show that

placid skiff
slate swan
#

ofc it's wrong

#

client = discord.ext.commands.Bot(command_prefix = your_prefix)

placid skiff
#

Yes 😂

slate swan
#

then why don't you use @supple mortar

placid skiff
#

I use slash command so i don't use the prefix lol

slate swan
#

commands.Bot not commands.bot

#

also

slate swan
placid skiff
slate swan
#

@placid skiff

placid skiff
#

BRUH HAHAHA he is right then

slate swan
#

thought so

#

@raven peak

placid skiff
#

You declare your Bot object as bot

So you have always to use @bot and not @client

slate swan
#

How do I make my bot speak through the command

#

I'm new to this group

#

I don't understand either

slate swan
#

yes

#

like send a text-to-speech message or say something in a voice channel?

#

what do you have already?

#

And like !say and Bot speaks tended?

#

And like !say test

And the Bot speaks Test

did you understand?

#

in a voice channel

tough wagon
#

how can i stretch the button to the whole line?
like this

slate swan
#

no idea about buttons

#

what's the problem aa_rav

#

well elaborate

#

nothing happens?

#

do you have an on_message by any chance?

#

hey hey, how to get the userid in a decorator??? I wanna do my own function, but since you can just get the context in it... how?

#

you wanna make a custom check?

#

yes

#

show code then

slate swan
#

you didn't call command

#

but how if the crx is not defined (since its the decorator=

#

@raven peak not @bot.command

dapper cobalt
unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

slate swan
#

uhh

slate swan
#

I see ok ty

#

you're welcome

dapper cobalt
tough wagon
slate swan
#

send the full error

#

ctrl + v

#

yea rhanks

#

oof

tough wagon
slate swan
#

how i can make it ? how can I take such a nickname format with a digital one?

tough wagon
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=Embed.Empty, icon_url=Embed.Empty)```
Sets the author for the embed content.

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

if I use it {member.name} bot doesn't copy the user's digits

tough wagon
#

it is just member

#

!d discord.Member

unkempt canyonBOT
#

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

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
tough wagon
#

@slate swan

slate swan
tough wagon
#

so {str(member)} or just {member} cause fstring converts

slate swan
#

... Man thank you

tough wagon
#

np

tough wagon
maiden fable
#

\u200b

#

Just add this in the button content

tough wagon
#

@maiden fable

maiden fable
#

Yups, it's a hairline space

tough wagon
#

wdym, how should I use it bruh

maiden fable
#

Or just try adding simple spaces

tough wagon
#

@maiden fable I don't understand you, I just tryied \u200b and spaces it didnt work

maiden fable
#

@tough wagon just try adding loads of \u200b chars...

slate swan
#

tough wagon
#

_ _

tough wagon
slate swan
#

hahaha

#

mortal

maiden fable
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1635014367:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 16 consecutive newlines in 10s).

maiden fable
tough wagon
#

i finally found it -

slate swan
# slate swan

I bet u used a selfbot cuz when a bot sent embed msg u can remove the embed and it gon look like that

maiden fable
#

And what if I say u r wrong? Prove that he's using a self bot

slate swan
maiden fable
slate swan
tough wagon
#

bruh

silk mauve
#

Guys, how can I do that my bots writes in a embed emoji of my server

#

Like this one

silk mauve
#

Like

#

This

silk mauve
#

Ah

silk mauve
#

Is that wrongß

#

?*

maiden fable
#

I don't think so

#

Uhhhhhh, I don't think u can have an emoji in title

#

Try doing in the description

slate swan
#

Emojis don't work in titles and footers

maiden fable
#

Yea thought so

silk mauve
#

alr

slate swan
#

Not custom emojis at least, stuff like 🤧 work tho

silk mauve
#

ty

maiden fable
#

Ok discord broke

#

Or my phone is broke

silk mauve
maiden fable
#

See the emoji

silk mauve
maiden fable
silk mauve
#

No

maiden fable
#

Oh, hmm

#

Wait, I think it's a discord bug... Since dyno bot also experiences that

dapper cobalt
maiden fable
#

Dyno also has the same problem

silk mauve
#

Mhmm..

lusty swallow
#

oof

strong kettle
#

How do I find out who created the specific channel?

maiden fable
#

!d discord.AuditLogEntry

unkempt canyonBOT
#

class discord.AuditLogEntry(*, users, data, guild)```
Represents an Audit Log entry.

You retrieve these via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").

x == y Checks if two entries are equal.

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

hash(x) Returns the entry’s hash.

Changed in version 1.7: Audit log entries are now comparable and hashable.
slate swan
#

Hey

maiden fable
#

Hi

jade pebble
#

how do I pass a image to my discord bot?

maiden fable
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

jade pebble
maiden fable
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

maiden fable
#

Wait what

#

!d discord.Asset.save

unkempt canyonBOT
#

await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Saves this asset into a file-like object.
maiden fable
#

There

jade pebble
#

thank you

maiden fable
#

And

#

!d discord.Message.attachments

unkempt canyonBOT
maiden fable
#

This returns the list of discord.Asset objects

jade pebble
#

so ```python
@bot.command(brief='MF')
async def MF(ctx,attachment):
await ctx.send('pong')

maiden fable
#

Nah

#

ctx.message.attachments returns the list of discord.Attachment objects

jade pebble
#

ok

#

who would I do that?

maiden fable
#

?

jade pebble
#

how would I just download or get the url to the attached file?

maiden fable
#

Bro, I told u the whole way

#

Just loop through ctx.message.attachments and call the save method

jade pebble
#

ahh never mind

maiden fable
#

Cool

silk mural
#

can anyone help me run someone elses python bot

#

code is complete but i need a little help understanding it

velvet crest
#

i have a custom subclassed help cmd in a cog, is there any way i can use its functions in other cmds. for eg a user doesnt provide the right subcommands for a cmd so i could do like send cmd help for the context cmd

hasty iron
#

!d discord.ext.commands.Context.send_help

unkempt canyonBOT
#

await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").

Note

Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
velvet crest
safe temple
#

what are you guys using for bot development in python?

kindred epoch
#

!pypi disnake

unkempt canyonBOT
slate swan
#

^^

devout iris
#

How can i set custom status?

delicate flax
#

What type of status?

delicate flax
devout iris
#

Not game

#

Custom status

delicate flax
#

I think you can't

devout iris
delicate flax
#

Yes I see

devout iris
devout iris
delicate flax
#

I think you can't set a custom status of a bot

devout iris
#

i can

delicate flax
#

I don't know how so

leaden jasper
#

see the top solution

devout iris
#

Ahh smh

#

Sorry :/

delicate flax
#

Do you know how to get attachment url?

hasty iron
#

!d discord.Attachment.url

unkempt canyonBOT
#

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

devout iris
#

How can i set embed message?

leaden jasper
leaden jasper
devout iris
#

Create

leaden jasper
#

!d discord.Embed

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.
devout iris
#

Can i do it without class?

leaden jasper
#

a class?

#

No that's the docs

#

you use that class

delicate flax
devout iris
#

Wait i will say details
Actually i want to send message as embed from bot

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

hasty iron
#

!d discord.abc.Messageable.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**.
hasty iron
#

embed kwarg which takes in an Embed object

leaden jasper
delicate flax
#

Do you know why when my bot send an embed, there is a on_message_edit event?

devout iris
#

Can u help me

delicate flax
#

Do you want to ping someone?

devout iris
#

No

#

Bot's ping

delicate flax
#

ok wait a second

devout iris
#

alr

delicate flax
#

round(bot.latency*1000,1)

slate swan
#

Just do int(bot.latency*1000)

devout iris
#

To where?

#

in embed message

slate swan
#

Wherever you want to show it

devout iris
#

i cloudn't make it still pfffff

#

is this wrong?

delicate flax
#

is there an error?

devout iris
#

no

kindred epoch
delicate flax
#

you forgot the ,

#

after the title

kindred epoch
#

^

delicate flax
#

like this : title = "Pingim",

devout iris
#

when i use command

delicate flax
#

the ,

#

like this : title = "Pingim",

devout iris
#

aaahh not legacy a sec

#

lmao my bad

delicate flax
#

lol

devout iris
#

it is working now tysm

slate swan
#

hello! May anyone help me with components who knows a bit more about it?

#

I am currently trying to get button input and so far I'm getting the click event and after that something happens. Now I got 2 buttons and want to know: how to find out which button was pressed?

#

button_ctx: ComponentContext = await manage_components.wait_for_component(bot, components=action_row)

torpid dew
#

hi, what is wrong with this code, the discord bot should output an animated emoji, discord doesn't let me send the emoji id so it outputs :Fire:.

@client.event
async def on_message(message):
  if message == 'wfire':
    await message.send(":Fire:")
#

thanks

slow fog
slow fog
#

its working?

slow fog
#

try and see

torpid dew
#

ok

#
@client.event
async def on_message(ctx):
  if ctx == 'wfire':
    await ctx.send(":Fire:")
#

didnt work

#

discord doesnt let me show the emoji id

#

but ik how to do it because i can do the add_reaction

slow fog
#

oh

torpid dew
slate swan
#

client.process_commands(message)

slow fog
#

isnt it the same code above

#

im not sure

#

i think you have to put the emoji id

#

and send it as a variable name

slate swan
slow fog
#

tbh i have never tried the buttons before

final pumice
#

im new to discord bots

slow fog
final pumice
#

so, do I need somewhere to host the bot?

slow fog
#

Oooooooooo

#

well

final pumice
#

or do i just pass code to it and it runs as is

slow fog
#

do you want it for free?

final pumice
#

wym

slow fog
final pumice
#

like, lets say I make a bot

slow fog
#

yes

#

you have the code of the bot

final pumice
#

Does it use the computing power from my computer

#

Or like how does it work

slow fog
#

yes it can be

final pumice
#

But what if I don't want that

#

What do i do?

slow fog
#

then you have to find a hosting server

final pumice
#

What is that?

slow fog
#

from sites

#

There are sites that provide a host service for your bot

torpid dew
final pumice
#

What do you do?

slow fog
#

hosting it on my computer

#

But the matter is different for you if you want to pay to subscribe or are looking for a free service but it is difficult to find a free service with all the required descriptions

final pumice
#

Does it take a lot of computing power to do?

slow fog
#

at all

final pumice
#

Okay, bc I do all of this on my laptop

slow fog
#

You can try and watch the usage

final pumice
#

And I don't want the bot to hinder my laptop's performance if I do host it on my computer

slow fog
slow fog
#

Try and see

final pumice
#

Okay, how do I host it on my computer?

slow fog
#

install the visual studio code

final pumice
#

I have that

slow fog
final pumice
#

I know all the necessary things for Python. I am just learning the Discord API rn

slow fog
#

library

final pumice
#

Yes i do

slow fog
#

now open the that have your disocrd bot code and run it

final pumice
#

Don't have any at the moment

slow fog
#

oh

final pumice
#

Do I just run it once i do?

#

And it will use my computer to host?

slow fog
#

you gonna run it once then its will be online but when you close the program or close your computer its gonna be offline

slow fog
final pumice
#

Alright

#

One thing

slow fog
#

yes

final pumice
#

I heard some people use the cloud to host on

#

Does that work?

slow fog
#

ofc

#

yea

final pumice
#

And that's free?

slow fog
#

im not sure but most need to pay

final pumice
#

Alr thanks

slow fog
#

What I know is that there are two free services

#

replit: but it makes your bot code visible to everyone

final pumice
#

What's the other

slow fog
#

heroku: free and i dont think it will make your code visible to everyone and thats cool but its complicated

final pumice
#

Hm okay

#

Are there any paid hosting services that you know of that are good?

slow fog
#

there is many

final pumice
#

Do any of them stand out compared to what you have heard from others?

slow fog
#

oh the replit itself you can paid and make your code private

final pumice
#

Interesting

slow fog
#

The paid service is always integrated and without problems

final pumice
#

Alright thanks

slow fog
#

on replit

#

This service is paid in replit

#

and you can search for other sites

final pumice
#

Okay. Thanks a lot

#

This will help me very much

slow fog
leaden jasper
# final pumice Are there any paid hosting services that you know of that are good?

If you need to run your bot 24/7 (with no downtime), you should consider using a virtual private server (VPS).
This is a list of VPS services that are sufficient for running Discord bots.

https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.

There are no reliable free options for VPS hosting. If you would rather not pay for a hosting service, you can consider self-hosting. Any modern hardware should be sufficient for running a bot. An old computer with a few GB of ram could be suitable, or a Raspberry Pi (any model, except perhaps one of the particularly less powerful ones).

Linode

Our mission is to accelerate innovation by making cloud computing simple, affordable, and accessible to all.

next vapor
#

How would you get someones discord username from id

final pumice
#

Wouldn't a hosting service be better than using my computer?

#

Also, thank you for that entire list

#

Very much appreciated

slow fog
final pumice
#

Also @slow fog

#

I found this thing in repl.it which gives you repl.it pro for free with the Student Development Package

slow fog
final pumice
#

I am going to try to do that since I am currently enrolled

#

I sent an application to GitHub

#

For the package

slow fog
#

cool

slow fog
#

gonna kick the user from his id too

next vapor
#

No like

#

I have someones ID and i wanna get their discord username

leaden jasper
#

The problems with the free 24/7 hosting options are

Replit:
• Code is public
• Shared servers so if someone else's bot gets ratelimited yours will be too
• Random restarts

Heroku:
• runs for 21 days/month without credit card registration

#

@final pumice

next vapor
#

i tried using bot.get_user() but that returns nothing

leaden jasper
final pumice
#

That sounds like a good idea

slow fog
#

try

leaden jasper
final pumice
#

But let's say they want to host it on their computer

#

I would have to give them the code, right?

#

@leaden jasper

leaden jasper
#

Yes

slow fog
#

I just understood

#

lol

leaden jasper
slow fog
#

he want his name

leaden jasper
#

and id is 288098711400218624 for example

slow fog
#

oh

next vapor
#
@bot.command()
async def verify(ctx, ign):
    id = ctx.author.id
    print(id)
    discordHash = bot.get_user(str(id))
    print(discordHash)

If i run this and do the command the ID is outputted but discordHash returns as None

#

Ohh

#

Also yeah i didnt inclue the await ctx send but that was irrelevnat

next vapor
#

that still returns None

slow fog
#

lol

#

i think this one

#

user = bot.get_user(user_id)

#

try

next vapor
#

alr

#

says the user_id isnt a thing

slow fog
#

put user: discord.Member above

#

with the ctx

leaden jasper
#

@next vapor str(ctx.author)

#

to get [Blaze]#9457

next vapor
#

Ohhh ok

slow fog
#

@bot.command()
async def verify(ctx, ign, user: discord.Member):
id = ctx.author.id
print(id)
discordHash = bot.get_user(str(id))
print(discordHash)

#

no wait

next vapor
#

Alright that worked thanks

slow fog
#

which kne

next vapor
#

imps

slow fog
#

one*

boreal osprey
#
@bot.command()
async def slowmode(ctx, seconds: int):
    await channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Slowmode delay set to {seconds} seconds.")
slow fog
slow fog
boreal osprey
#

ye i saw

slow fog
#

the ctx.channel.edit

boreal osprey
#

damn

slow fog
boreal osprey
#

i alr fixed my code

leaden jasper
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
leaden jasper
#

@boreal osprey

boreal osprey
#

i alr fixed it

indigo forum
#

how do i

#

give a specific role to a user

#

temporarily

#

like a mute

#

for a specific specified time: 1 minute

leaden jasper
#

@indigo forum You need to save the timestamp preferably in a database and have a task that checks if the time is up periodically to remove the role

indigo forum
#

uhh no thanks i prefer basic mute

stable delta
#

well there is a more basic way, however it stops working after the code is refreshed

indigo forum
#

what

#

what does after the code is refreshed mean

stable delta
#

after giving the person the role, await asyncio.sleep(x) for the time given

leaden jasper
#

when you restart the bot i guess

stable delta
#

and after that line just remove the role

indigo forum
#

then

#

wait what

#

i got an email from deezer to reset my pass

slate swan
indigo forum
#

do you know when did i request the pass reset?

#

a lot of hours ago

#

this mornng

#

rn its 1:58 am

#

here

leaden jasper
#

Maybe their website was down

#

and came back up just now

indigo forum
#

talking about the bot...

leaden jasper
#

your bot is deezer?

indigo forum
indigo forum
#

and mutes for 1 minute to who sent the rickroll

leaden jasper
#

pretty boring

indigo forum
#

but the mute not implemented yet

indigo forum
#

well

#

what i wanna do is:

  • check if the role "muted" exsists

    • if not, create it
  • give the role to the user

#

and then

#

convert that to python code

leaden jasper
#

Is that all your bot is going to do?

indigo forum
#

no

#

also say

#

rickroll alert

leaden jasper
#

what the text "rickroll alert"?

indigo forum
leaden jasper
#

Anything else

indigo forum
#

uhh no

leaden jasper
indigo forum
#

when rickroll is detected

leaden jasper
#

are u making the bot for fun?

indigo forum
#

... not really

leaden jasper
#

so it's serious

indigo forum
#

more or less

#

yeah

#

but

#

i got an idea

leaden jasper
#

how do you plan to host it

#

i mean a lot of effort for a bot that just detects rickrolls...

indigo forum
#

anyways i got an idea for the bot

leaden jasper
#

that is only 21 days per month without cc registration

indigo forum
indigo forum
leaden jasper
indigo forum
#

I. DO. NOT. CARE.

leaden jasper
#

soo you dont want the bot to be online?

#

...

indigo forum
#

yes

#

99% of the month online

leaden jasper
#

i said you dont want*

#

a negative

indigo forum
#

what.

leaden jasper
#

You answered "yes"

#

but contradicted that yes in your next message

#

So I'm confused.

indigo forum
#

no

#

the yes contradicted the no in your message

leaden jasper
#

My message was a question

#

not a statement

indigo forum
indigo forum
#

and

leaden jasper
#

You cant contradict a question

#

only answer it

indigo forum
#

ok

#

forget

leaden jasper
#

done

indigo forum
#

now

#

2 things to add to the bot

#

-make a "muted" role if it doesnt exist - ensure that the muted role has not admin related perms and admin perm and it doesnt have permission to send messages - add it to the user for 1 minute
-add a /report command so the bot uses an email and a password to email my alt email account with a brand new rickroll link (fake videos)
-the bot double checks it has admin permissions, otherwise, it automatically leaves the server

leaden jasper
#

You also need to consider if the bot has permission to create and manage roles as well

indigo forum
leaden jasper
#

They could edit the url and mess up the permissions

#

but i guess it doesnt crash ur bot so dw about it

#

It's going to flood you with errors though if someone finds out how

indigo forum
leaden jasper
#

rickroll bot with admin pwrmissions!?

indigo forum
#

ANTI rickroll bot

leaden jasper
#

I don't think anyone sane would invite this bot to their server

indigo forum
#

uhh

leaden jasper
#

aside from test servers

#

Why does it need admin!!!

indigo forum
#

Will you help me or discuss everything I say?

leaden jasper
#

both i guess

#

I'm just pointing out that you won't get that many invites if your bot requires admin permission

indigo forum
#

can you translate this to human languag ?
message.guild.roles.cache.get('ROLE-ID').members.map(m=>m.user.id);

leaden jasper
#

I have never heard of cache.get

indigo forum
#

oh wait

visual island
#

its js

leaden jasper
#

is that old code?

indigo forum
#

v12

leaden jasper
#

o

indigo forum
#

sorry i searched for js instead of py

#

this?

#

discord.utils.get(guild.roles,name="Supporter")

visual island
#

sure

indigo forum
#

but

#

how can i check if

#

that is true or false

#

and

#

how to implement it in my bot

visual island
#

so check if its None

indigo forum
#

but

#

how

#

wait

#

!e ```py
discord.utils.get(guild.roles,name="Supporter")

unkempt canyonBOT
#

@indigo forum :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 'discord' is not defined
visual island
#

if discord.utils.get(...) is None

leaden jasper
#

import discord

#

You cant test here actually

indigo forum
#

!e ```py
import discord
from discord.ext import commands
discord.utils.get(guild.roles,name="Supporter")

unkempt canyonBOT
#

@indigo forum :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
slate swan
#

why am I getting this error with bot.run on windows but not linux

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002A1B4FCA790>
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
hollow agate
#
@client.command()
async def timestamp(ctx):
    x = datetime.now()
    timestamp = x.timestamp()
    await ctx.send(f'<t:{timestamp}:t>')``` How can I round the timestamp? It doesn't work with decimals for whatever reason.
indigo forum
#

wait

visual island
indigo forum
slate swan
hollow agate
visual island
#

python has a bug with proactor thing on windows

indigo forum
visual island
hollow agate
#

Wat

slate swan
#

so why do I get that error ?

hollow agate
visual island
#

show your code

leaden jasper
slate swan
#

wait nevermind I fixed it im literally stupid I made token a string which interfered with my error catching

leaden jasper
#

because if its a public bot, you should use a db to store the muted roles for each server

#

@indigo forum

indigo forum
visual island
#

just use asyncio.sleep

hollow agate
leaden jasper
leaden jasper
#

which is a lot since he uses heroku

indigo forum
leaden jasper
#

they restart every 24 hours

visual island
#

oh, that's a problem then

indigo forum
hollow agate
#
db = await aiosqlite.connect('database.db')
    cursor = await db.execute('SELECT time_expired FROM bans')
    a = await cursor.fetchall()
    for row in a:
        await asyncio.sleep(1)
        #print(row[0])
        stored_timestamp = row[0]
        if row[0] <= DT.datetime.now().timestamp():
            muted = discord.utils.get(guild.guild.roles, name="Muted")``` So, I'm storing `time_expired` and `user_ids` in a database. How can I get the `user_ids` where the `muted` role is defined?
indigo forum
#

get user_ids from database

#

xdddd

hollow agate
indigo forum
#

i dont know

leaden jasper
# indigo forum what.

If you're using heroku to host your bot for free, they will restart your bot once a day so your timed mutes with asyncio.sleep(x) will break

#

so you should store timestamps in a database

pliant gulch
#

Keep in mind since heroku uses an ephemeral file system you will be required to use a database that isn't hosted on heroku

#

As it will reset all the data after reset

hollow agate
#

role1 = discord.utils.get(message.guild.roles, name='Members') Very dumb question, but how can I use this in a task loop (I defined the guild as guild)

leaden jasper
#

!d discord.ext.tasks.loop @hollow agate

unkempt canyonBOT
#

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

@indigo forum its their policy i guess

indigo forum
#

oh and

#

i know its possible to host a discord.js bot in a website

#

i mean

#

inside the website

hollow agate
#

It's a free service and they transfer your hoster quite often-- get a vps or a cheap hosting

indigo forum
#

not even a cent

hollow agate
#

You will need to learn databases xd

#

I use a hosting that's like $2 for 3 months and never restarts. lol

indigo forum
#

i said

#

no pay

#

but

#

anyways

#

uhh

#

how do i code the database

hollow agate
#

Go watch a youtube tutorial, there's quite a few databases you can choose from

#

SQLite is the easiest for me and generally the easiest.

#
cursor = await db.execute('DELETE FROM warns WHERE time_expired=?', (row[0], ))``` How can I make it just delete the time_expired data and not the whole row/column?
indigo forum
# hollow agate Go watch a youtube tutorial, there's quite a few databases you can choose from

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
hollow agate
#

That's part 5... go get a part 1 xD

pliant gulch
#

This won't persist the data

#

As again, heroku has an ephemeral file system

hollow agate
#

True, you're gonna need to host a database somehwere else

indigo forum
hollow agate
indigo forum
hollow agate
#

I don't know nor care-- figure it out xd

pliant gulch
#

github is not a server

indigo forum
pliant gulch
#

And how are you supposed to host a database on there?

indigo forum
#

uhh

hollow agate
#
cursor = await db.execute('DELETE FROM warns WHERE time_expired=?', (row[0], ))``` How can I make it just delete just the `time_expired` data and not the whole row/column?
indigo forum
pliant gulch
#

I still don't see how that solves the problem

indigo forum
hollow agate
#

Uhhh

#

I'm not sure that's how SQLite databases work

leaden jasper
indigo forum
#

where is it possible to host a sqlite database?

#

for free

hollow agate
#

You can't connect to a sqlite externally

leaden jasper
#

@indigo forum just use heroku's database

indigo forum
#

how

pliant gulch
hollow agate
#

I mean, yeah, I reckon you could

leaden jasper
#

search for Heroku Postgres

indigo forum
leaden jasper
#

free plan

Row Limit10,000

Storage Capacity1 GB

#

that's all you need for a rickroll bot

leaden jasper
indigo forum
#

NOT RICKROLL

#

and

#

btw do i have to add the heroku postgres to the heroku app itself or make another one?

leaden jasper
#

it doesnt matter

indigo forum
#

ok

leaden jasper
#

Make sure the database exists somewhere, get the credentials to connect to the database

leaden jasper
#

Imgur?

#

cant you attach files?

#

screenshots*

indigo forum
#

this is mine i guess

#

oh

#

i found credentials

#

with my super 🧠

shy roost
#

yo guys, how can I check if a specific user receiving a message has the permission to do so? I'm making a report feature for a moderation bot, and I would like to make it so that when the bot sends the report message to the person the person who used the command wanted to, that person has to have admin perms first.

pliant gulch
pliant gulch
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.
indigo forum
#

ill make a group for helping me cause a lot more people needs help and i wanna do this as quick as i can

#

ill add friends

#

accept the request

leaden jasper
shy roost
#

wait so can I just do this: ```py
if staff.guild_permissions() == "administrator":
do something

#

nevermind, figured it out. Thank you guys !

leaden jasper
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

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

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

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

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

makes things neater, less indents

pliant gulch
#

If a specific user receiving a message has the permissions to do

slate swan
#

any1 know why theres a red line?

pliant gulch
shy roost
leaden jasper
#

they meant for themselves using the command

pliant gulch
leaden jasper
#

they are using a report system/dm support im guessing

pliant gulch
leaden jasper
#

which doesnt make sense.

shy roost
#
@commands.command()
    async def report(self, ctx, message: str, staff: discord.Member):
        if staff.guild_permissions.administrator or staff.guild_permissions.moderator:
            await staff.send(message)
            embed = discord.Embed()
            embed.add_field(name="⠀", value="Message successfully sent!")
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed()
            embed.add_field(name="Oops!",value="Message could not be sent, as the person you tried to send it to, is not a staff member.")
            await ctx.send(embed=embed)
pliant gulch
#

So I was right

indigo forum
#

c u tomorrow ||@leaden jasper@pliant gulch@hollow agate||

pliant gulch
shy roost
#

i'm trying to make a report command, where someone can submit a message into the command as a parameter, then the bot will dm the message to a moderator, why isn't this working, and I made a server for me and my friend to test this and he is an admin, but i'm getting a forbidden error saying I can't send messages to them, but i'm the server owner?

pliant gulch
#

That isn't a valid permission

shy roost
pliant gulch
#

The guild_permissions.administrator part is correct though

leaden jasper
#
!SendDM andy Hello.

you're saying you need to check if andy has admin permissions present which is redundant.

whereas i'm saying in order to use the command !senddm you need admin permissions which makes sense

pliant gulch
shy roost
leaden jasper
pliant gulch
#

!d discord.Member.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**.
shy roost
pliant gulch
shy roost
pliant gulch
#

receiving, idk sounds pretty specific

pliant gulch
#

So you need to await it

shy roost
#

i did

pliant gulch
#

Ok then that should work

shy roost
#

I did py await staff.send(message)

pliant gulch
#

It is*

#

Yea just saw that part

shy roost
#

yeah, but it's still saying that I can't send the report message to my friend who's an admin in my server, even though i'm the server owner lmao

leaden jasper
#

Normally dm support systems redirect messages to a channel for all staff to see. His system is inefficient because if a staff member is busy/offline/afk you won't know and you need to run the command multiple times for other staff members

shy roost
pliant gulch
#

Oh wait,

#

make sure the person you are trying to DM Has DM's on

shy roost
#

how about this. how can I make it so that I can just make the bot automatically start a dm channel with every mod and dm this message to them?

shy roost
pliant gulch
#

Sounds quite spammy I would just do await staff.send

pliant gulch
#

try-except will do

shy roost
pliant gulch
#

Yea

shy roost
#

like this: ```py
try:
staff.send(message)
except Forbidden:
await ctx.send("The staff member you wanted to send the message to, has dms turned off!")

pliant gulch
#

Yes

shy roost
#

alright, let me give that a shot

pliant gulch
#

Assuming Forbidden is discord.Forbidden

slate swan
#

@pliant gulch whats the difference between else and expect

#

im confused abt tht

pliant gulch
#

Does what the word means,

#

Except goes with a try statement

slate swan
#

ohhh shit

pliant gulch
#

It will try the code, then except an error

slate swan
#

now i understand

pliant gulch
#

If the error is received it handles it

shy roost
slate swan
pliant gulch
#

👍

shy roost
#

@pliant gulch really basic question, I have the bot working, but I can only set the parameter message to be only one word, otherwise it sets whatever the word after the first word is, to be the staff parameter, how can I fix this?

pliant gulch
pliant gulch
#

You can use the * which in discord.py consumes rest

pliant gulch
#

I.e (arg1, *, args)

shy roost
#

wait so I should delete the message parameter and put *?

pliant gulch
#

Args will be able to take however many words

#

Whilst arg1 can only take one

pliant gulch
shy roost
#

ah okay, so I should put "*" in place of the "message" parameter?

#

how will the bot know when to count the input as a staff parameter?

vague zealot
#

!unsubscribe

pliant gulch
#

Which is why I said you will need to rearrange the signature

shy roost
#

ah okay, so the * should go before whatever it wants to consume the rest of?

pliant gulch
#

Yes

shy roost
#

ah okay, that's really nice, thank you for the clarification.

pliant gulch
#

So for here you pass staff first, then the message

shy roost
pliant gulch
#

Yes

shy roost
#

ah okay, and I can just call the message parameter as normal right?

#

same as before right?

pliant gulch
#

Same as before, but staff has to be given before it

#

But with it you can pass multiple words

shy roost
pliant gulch
#

Sure

shy roost
#

@pliant gulch is there a way I can make an automute command? like check between a start time, and the end time, and how many messages they sent throughout the time period, and give them a muted role if they do exceed a limit?

pliant gulch
shy roost
#

how can I do so?

pliant gulch
#

That is if you know tasks, and understand how to do databases

shy roost
#

nevermind, i don't

#

i'll figure it out later

pliant gulch
#

Or have you setup a database before

shy roost
#

do you know how I could make a command that can execute codeblocks that are passed to it?

shy roost
shy roost
#

using the exec() function?

#

and providing tracebacks for errors that occur?

pliant gulch
pliant gulch
#

Uhh idk how easy it will be to explain but

#

Exec can take a dictionary, this is where you put variables in that you want to be able to reference

#

You then want to create a str and pass that to exec beforehand the dictionary which is your function

#

i.e ```py
exec(f"async def eval():\n{code}")

shy roost
#

and I would pass their code in the "code" parameter?

pliant gulch
#

Then you can pass your dictionary of variables

pliant gulch
#

first you need to clean up the codeblocks

#

You can do this via strip

#

As the parameter will look like tildas

#

!e py codeblock = "code stuff```"
print(codeblock.strip("`"))

unkempt canyonBOT
#

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

001 |   File "<string>", line 1
002 |     codeblock = "
003 |                 ^
004 | SyntaxError: unterminated string literal (detected at line 1)
pliant gulch
#

ah I can't do it on discord

shy roost
#

damn okay

#

could you just give an example of a basic code being passed to the command, in the form of a dictionary, and that should help me better understand the meaning of what you are trying to say.

pliant gulch
pliant gulch
#

replacing code

pliant gulch
unkempt canyonBOT
#

exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
pliant gulch
#

Keep in mind you very much want to make sure this command can only be ran by you

#

!d discord.ext.commands.is_owner

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
pliant gulch
#

Use this decorator and then it will only allow you to run the command

shy roost
#

how?

pliant gulch
#

Well someone can remove all the files from your computer/where you host the bot

shy roost
#

damn okay

pliant gulch
#

or any other thing that can be executed by code

shy roost
#

I can just make it so that only people with admin perms

#

can run it, this way not only me can run it, but people who I trust

pliant gulch
#

If you trust your admins enough sure ig

shy roost
#

okay, let me try to write this command

pliant gulch
#

You just need to use has_permissions and pass in administrator=True

shy roost
#

ah okay, also, what do you mean here?

shy roost
pliant gulch
#

There it uses the variable code

shy roost
#

ah okay, I understand.

pliant gulch
#

👍

pulsar shell
#

Hey Andy,

pliant gulch
#

hi sleep

shy roost
#

can I use try-except to simply use ```py
except Exception as e:
say something

pliant gulch
#

Uh

shy roost
#

in case the evaluated code returns errors?

pliant gulch
#

You could ig

shy roost
pliant gulch
#

Yea, you can use traceback module to format the exception and send that back to discord

pliant gulch
shy roost
#

could you give an example? (sorry, i just have never used some of the things that you are mentioning lol)

shy roost
pliant gulch
#

variables being the dictionary of variables you made

#

which can be referenced in the codeblocks

#

i.e if I had py variables = {"stuff": 1} I could then reference it in the codeblock via stuff

shy roost
#

yeah, i don't think i'm going to do all those steps if they aren't necessary to make a very basic evaluate command, since that's all I want for now, since I have other things to work on lol

#

@pliant gulch how could I use the traceback module to format any errors returned from the command user's code?

pliant gulch
#

!d traceback.format_exc

unkempt canyonBOT
#

traceback.format_exc(limit=None, chain=True)```
This is like `print_exc(limit)` but returns a string instead of printing to a file.
pliant gulch
#

Import traceback and use this

shy roost
pliant gulch
#

You just call it and it should capture any errors iirc

#

Then it returns a string

shy roost
#

ah okay, let me try it out

#

@pliant gulch py @commands.command(aliases=["e", "eval"]) async def evaluate(self, ctx, *, code): codeblock = f"{code}```"
end_code = codeblock.strip("`")
evaluated_result = exec(f"async def eval():\n{end_code}")
captured_errors = traceback.format_exc(limit=None, chain=True)
embed = discord.Embed()
embed.add_field(name="Code evaluation finished!", value=f"{captured_errors}")
await ctx.send(embed=embed)

#

tried this code, and I got a indention error

pliant gulch
shy roost
#

the traceback is leading to this line: ```py
evaluated_result = exec(f"async def eval():\n{end_code}")

pliant gulch
#

Hmmm I don't see a problem here? Can you print end_code

shy roost
#

okay

pliant gulch
#

ah wait

#

I know

#

Its because the codeblock after cleaned, the code is not indented

shy roost
#

LMAO

#

I JUST REALIZED SOMETHING

pliant gulch
#

I think you need textwrap.indent for that

shy roost
#

okay, I just realized that i was outputting the captured errors i got, not the result

shy roost
pliant gulch
#

You will need to redefine end_code and assign to to textwrap.indent(end_code, prefix="\t")

shy roost
pliant gulch
#

Well, you can do end_code = what you had originally

#

then under that redefine it as end_code = textwrap.indent(end_code, prefix="\t")

slate swan
#

How do you use jumpurls

pliant gulch
shy roost
#

@pliant gulch after calling this variable: ```py
evaluated_result = exec(f"async def eval():\n{end_code}")

#

in this line: ```py
embed.add_field(name="Code evaluation finished!", value=f"{evaluated_result}")

slate swan
#

How do you make these

#

Jump urls

shy roost
slate swan
#

yo so im making a giveaway bot

#

and the giveaway section works

#

but the reoll bit doesnt

#
    pos = ["s","m","h","d"]
    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
    unit = time[-1]
    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2
    
    return val * time_dict[unit]

@bot.command()
@commands.has_role('👑CEO👑')
async def giveaway(ctx):
    await ctx.send("Lets start with this giveaway! Answer these questions within 15 seconds! ")
    questions = ["Which channel should it be hosted in? ",
                            "What should be the duration of the giveaway?  (s|m|h|d)",
                            "What is the prize of the giveaway?"]
    answers = []
    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel
    for i in questions:
        await ctx.send(i)
        try:
            msg = await bot.wait_for('message', timeout = 15.0, check = check)
        except asyncio.TimeoutError:
            await ctx.send('You didn\'t answer in time, please be quicker next time!')
            return
        else:
            answers.append(msg.content)
    try:
        c_id = int(answers[0][2:-1])
    except:
        await ctx.send(f"You didnt mention a channel properly. Do it like this {ctx.channel.mention} next time.")
    channel = bot.get_channel(c_id)
    time = convert(answers[1])
    if time == -1:
        await ctx.send(f"You didn't answer the time with a proper unit. Use (s|m|h|d) next time!")
        return
    elif time == -2:
        await ctx.send(f"The time must be an integer. Please enter an integer next time.")
        return
    prize = answers[2]
    await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
    embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = 0xA5FF1C)
    embed.add_field(name = "Hosted by: ", value = ctx.author.mention)
    embed.set_footer(text = f"Ends {answers[1]} from now on!")
    my_msg = await channel.send(embed=embed)
    await my_msg.add_reaction("🎉")
    await asyncio.sleep(time)
    new_msg = await channel.fetch_message(my_msg.id)
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won {prize}")

@bot.command()
@commands.has_role('👑CEO👑')
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
    try:
        new_msg = await channel.fetch_message(id_)
    except:
        await ctx.send("The id was entered incorrectly.")
        return
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won {prize}!")```
pliant gulch
#

There might be another way

slate swan
#

That doesn't seem to bad send the errors

pliant gulch
slate swan
#

it says prize is not defined when i reroll

#

does anyone know why

shy roost
#

@pliant gulch so I would have to define a dictionary beforehand called "variables" and what should I put in it? could you walk me through it?

pliant gulch
#

You don't need a variables

#

I was just showing that as an example

#

exec will make a function eval and you call that

#

i.e in your embed you call eval()

shy roost
#

could you give me an example?

pliant gulch
#

eval()

shy roost
#

can you vc rn?

pliant gulch
#

exec makes the eval function

#

I can't vc right now

#

!e ```py
exec("def eval():\n\tprint(2+2)")
eval()

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

4
pliant gulch
#

Oh you might want to change the name if you don't want to overwrite eval as well

shy roost
slate swan
#

so can anyone help me with my code then or what

shy roost
#

and replace "async def eval():"?

pliant gulch
#

well, evaluated_result is worthless here

#

as exec returns None

#

Just, wherever you are sending the return of the command to

shy roost
pliant gulch
#

i.e in an embed

#

you would call eval

pliant gulch
#

As it only returns whatever you returned

shy roost
#

and i added the evaluated_result variable as a field in an embed, then returned that embed, which returned none.

slate swan
#

great thanks for the help

shy roost
pliant gulch
#

if you did print it will return None

#

Check the terminal and you will see the print

shy roost
pliant gulch
#

but if you want something returned you need to return it

#

return 2+2 in your eval command

slate swan
pliant gulch
#

and it should return