#discord-bots

1 messages · Page 920 of 1

silent ermine
#

how do I update it for the server id? would it be like var = pilot[str(ctx.guild.id)] and then its var.update(dict)?

hasty raptor
#

Do I need to change command prefix

torn sail
#

No

silent ermine
torn sail
#

You won’t Change command prefix

hasty raptor
#

O ok

torn sail
silent ermine
supple thorn
silent ermine
silent ermine
supple thorn
#
pilot.update(dict)
#

If you want to update the guild id

silent ermine
silent ermine
supple thorn
supple thorn
silent ermine
silent ermine
supple thorn
#

Instead of changing it

silent ermine
supple thorn
#

Alright

silent ermine
supple thorn
silent ermine
supple thorn
#

Okay

silent ermine
supple thorn
silent ermine
supple thorn
#

Man this sucks ass

#

Just learn a database please

silent ermine
#

ok ty tho

supple thorn
#

It's better than this and it's like json

silent ermine
slate swan
#

sorry to respond to this so late but what is the value of disnake? And how can I add a image to it?

slate swan
#

disnake is a module?

#

!e

print(__import__("os"))
unkempt canyonBOT
#

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

<module 'os' from '/usr/local/lib/python3.10/os.py'>
supple thorn
clever fable
#

Does anyone know how to make a discord bot run a python script?

sick birch
clever fable
#

Thanks

slate swan
#

does anyone know how to add details for the game activity in discord bot like this?

pliant gulch
#

discord bot's don't support rich presence

slate swan
#

wait so how do I do it?

sick birch
#

You can have a simple "playing X" or something like that but not rich presence

sick birch
slate swan
#

do you guys know any library that would enable me to do that?

sick birch
#

This is an API limitation

slate swan
#

oh right

sick birch
#

No library you use will let you do that

slate swan
#

sorry

#
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import asyncio
import random
from keep_alive import keep_alive
bot = commands.Bot(command_prefix='!')
client = commands.Bot(command_prefix='!')


#ENV
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

#Character
async def send_dm(ctx,member:discord.Member,*,content):
  await member.send(content)

#Output Functions
keep_alive()
bot.run(TOKEN)
#

After this I get the error:

"Ignoring exception in command None:"
"discord.ext.commands.errors.CommandNotFound: Command "send_dm" is not found"

Not sure what's going on as I'm new to python

supple thorn
#

uh

#

okimii you explain

slate swan
slate swan
#

tf is a deco

supple thorn
#

lol

slate swan
#

@decorator

#

and for the second part i probably just copy and pasted it twice

supple thorn
slate swan
supple thorn
slate swan
#

youtube tutorials from old indian men

#

plus stackoverflow

supple thorn
#

🗿

slate swan
#

thats what im sayin

sturdy raptor
#

Who wants to collect 5M

supple thorn
#

bank robbery?

sturdy raptor
#

No

slate swan
#

go collect some women

sturdy raptor
#

It’s being encouraged by us government

supple thorn
supple thorn
worldly bane
supple thorn
worldly bane
slate swan
worldly bane
slate swan
#

wait 5m bro

#

😂

final iron
sturdy raptor
#

I just saw a thing that us will pay 5M if the public civilians can track down the corrupt money they gave Russia and its largest holders with enough information to prosecute and where the money went… 5M reward

#

Trying to find the post but seems easy enough with all the shit they’re finding right now and taking over

final iron
#

!ot

unkempt canyonBOT
sturdy raptor
#

The question is who can make it happen

#

Ok @unkempt canyon my apologies

worldly bane
daring olive
#

so i have a ping command, and a very basic about/server command

#

what shall i add next? something super easy

inner epoch
#

Hey guys I wanna add a function to my bot but dont want to make it as a command just a normal function and call it and yea it still consists bot object
Example:

def function_name():
  channel = bot.get_channel(123)
  channel.send("Test")
function_name()

How can I do that?

worldly bane
daring olive
#

example?

worldly bane
daring olive
#

would that be easier than say a command that sends a random cat image 🐱

gaunt ice
#

hm

daring olive
#

from an API

worldly bane
#

random cat is easier lemon_pensive

gaunt ice
#

oh mah gawd its minaberry

daring olive
#

haha lemme do random cat then

#

it is i

inner epoch
slate swan
final iron
final iron
#

🗿

inner epoch
#
async def hello():
    channel = await bot.get_channel(123)
    print(channel)

Ok so I defined this one but still I have to call it after bot.run(token) so how to do that?

slate swan
#

get_channel isnt a coroutine

#

so no need to await it

inner epoch
#

Yea I did that

#

Is that the way?

final iron
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

final iron
#

This was the wallpaper command I made

#

It's not completely polished but it does work

#

I quit bot dev before I completely finished it

final iron
inner epoch
slate swan
slate swan
#

it seems like you did02MINE

inner epoch
#

@slate swan didnt get it can you pls show an example or maybe some reference

slate swan
unkempt canyonBOT
clever fable
#

@slate swan do you knowq how to make a bot run a file

slate swan
final iron
worldly bane
inner epoch
clever fable
slate swan
worldly bane
#

try using the os module

slate swan
final iron
worldly bane
#

!d os.system

unkempt canyonBOT
#

os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
clever fable
slate swan
clever fable
final iron
slate swan
worldly bane
clever fable
clever fable
#

want me to send an example 💀

final iron
daring olive
final iron
slate swan
worldly bane
final iron
#

Preferably in an embed

daring olive
final iron
clever fable
#

@worldly bane

worldly bane
#

is that even in discord pithink

slate swan
clever fable
#

no bruh

final iron
clever fable
#

im trying to get the input from discord

daring olive
slate swan
inner epoch
daring olive
# slate swan

do you permit the user to only run this on themselves?

slate swan
# daring olive

should add a timestamp, when the user was created at, the users roles etc

worldly bane
final iron
slate swan
worldly bane
#

slate2 slash commands look good for some reason

slate swan
slate swan
#

just use a dict and a kwarg

#
print("".join([_dict[a] for a in kwarg]))
worldly bane
#

this looks so smooth ngl

slate swan
#

yes

inner epoch
# slate swan yes

Umm is channel.send() await function too? Bcs when am defining that am facing issues

worldly bane
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
inner epoch
pliant gulch
worldly bane
# pliant gulch

I love how discord decided to show it with that bot's pfp 🗿

inner epoch
worldly bane
inner epoch
#

Aye wait

#

shows this RuntimeWarning: Enable tracemalloc to get the object allocation tracebac

worldly bane
#

you need to await it

inner epoch
alpine furnace
inner epoch
# slate swan which line
RuntimeWarning: coroutine 'hello' was never awaited
  self.function(*self.args, **self.kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
alpine furnace
#

Regardless of whether the target user is in the server

alpine furnace
#

Yes, my message is not related to what you said

pliant gulch
#

You can use the API to fetch a User, doesn’t have to be in a guild with the bot etc

alpine furnace
#

It would be a cool feature

worldly bane
#

and in the error is the solution

daring olive
worldly bane
alpine furnace
#

I see

inner epoch
#

Yea I was going through that wait ill check

daring olive
#

btw, i'm looking for the documentation of how to return the discord time stamps
but i suppose i just return the string <:whatever:> and discord does the rest

pliant gulch
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
pliant gulch
#

But yea you can return a string yourself as well, then the client will render it

slate swan
boreal ravine
sick birch
slim ibex
#

That’s fire

slate swan
#

new thing in the api update iirc

worldly bane
echo wasp
#

question how do you make the arg not required like this?

async def command(self,ctx,arg = None):
  ...more code  ```
slim ibex
#

That’s the way

worldly bane
#

🗿

slim ibex
#

Setting a default makes it optional

worldly bane
#

he answered himself 💀

sick birch
#

You already had it 😄

slate swan
slim ibex
#

🗿

echo wasp
#

lol better to be safe then sorry lol

inner epoch
#

@worldly baneMind if I pm?

worldly bane
inner epoch
worldly bane
inner epoch
slate swan
daring olive
#

so
default_avatar, this is the default avatar discord gives you if you don't upload anything
guild_avatar, this is the avatar if they have nitro and have set a specific pfp for the guild
display_avatar, this is the same as above, otherwise it's their global

is that right? if a user has a guild_avatar then their global pfp is not available thru the API?

slate swan
sick birch
slate swan
#

!d discord.Member.guild_avatar

unkempt canyonBOT
#

property guild_avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the guild avatar the member has. If unavailable, `None` is returned.

New in version 2.0.
slate swan
#

yup its an optional asset

daring olive
#

in my testing both gulid_avatar and display_avatar are both showing my guild-specific pfp only

#

reading the docs that sounds right

sick birch
#

Discord's API guild member object avatar is optional so discord.py has to calculate what it is by itself

daring olive
#

it doesn't sound like i'd be able to get my black/white global pfp (click my pfp)

#

but wait that can't be rigth

#

or no it is right, i think

inner epoch
#

@worldly bane @slate swan @final iron Thanks a lot guys for the help I finally figured out it and also learned something new!!

bleak karma
#
@bot.event
async def on_member_update(before, after):
    if before.status != after.status:
       return

    if str(before.status) == "online":
      if str(after.status == "offline"):
        return

    if str(before.status) == "offline":
      if str(after.status == "online"):
        return
        
    if before.activity != after.activity:
        req_act = "vanity url here"
        my_server = bot.get_guild(channel id)
        role_id = role id here
        role = my_server.get_role(role_id)
        if act := [activ.name for activ in after.activities if activ.type == ActivityType.custom and req_act in activ.name]:
            
            channel = bot.get_channel(channel id here)
            emb = discord.Embed(color=0xffffff)
            emb.description = f"""
thanks for the vanity wowow
          """
            emb.set_footer(text="vanity")
            if role in after.roles: 
              return
            else:
              await channel.send(f"<@{after.id}>", embed=emb)
              await after.add_roles(role)

        else:
              await after.remove_roles(role)

error:

  File "main.py", line 35, in <listcomp>
    if act := [activ.name for activ in after.activities if activ.type == ActivityType.custom and req_act in activ.name]:
TypeError: argument of type 'NoneType' is not iterable

help

slate swan
unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
slate swan
#

"but if they have a guild specific avatar then that is returned instead." yup

daring olive
#

ah those docs are better :x
disnake doesn't make that super super clear

slate swan
inner epoch
worldly bane
#

why use disnake when you can use discord.py if you are just starting lol

daring olive
#

nvm i was looking in the wrong place lol

slate swan
unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
slate swan
slate swan
daring olive
#

i was looking under disnake.User

slate swan
daring olive
#

i was test-driving disnake's setup guide thing

bleak karma
slate swan
#

ah

daring olive
#

i'm at a point where it doesn't matter which framework i use anyway

slate swan
#

disnake isnt bad lol

slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'NoneType' object is not iterable
bleak karma
#

oh

daring olive
#

so just to confirm, it's not possible for me to show in an embed both a user's guild-specific & global pfps

slate swan
#

!d disnake.User.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
daring olive
#

can i? playing with it right now


    @commands.slash_command()
    async def user(self, inter: disnake.ApplicationCommandInteraction):

in this context are inter.user & inter.author different?

#

they seem the same to me

slate swan
#

disnake makes inter.author the author of the interaction while some forks stick with dpy and use inter.user

#

samething lol

sick birch
daring olive
#

yeah using user didn't change anything

slate swan
daring olive
#

about to head to bed though Lsleep

slate swan
#

!d disnake.Interaction.author

unkempt canyonBOT
slate swan
spring flax
#

You need to subclass bot for overriding context right?

daring olive
#

btw is there 1 property that encompasses this {inter.author.name}#{inter.author.discriminator}

#

username#discrim

#

there probably is and i just missed it

spring flax
#

str(inter.author)

spring flax
slate swan
unkempt canyonBOT
#

disnake/interactions/base.py line 216

def user(self) -> Union[User, Member]:```
unkempt canyonBOT
#

disnake/interactions/base.py line 187

self.author: Union[User, Member] = MISSING```
daring olive
#

ic ic

slate swan
#

not sure why theres no method that returns only the avatar of the user class

spring flax
#

!d disnake.Member.guild_avatar

unkempt canyonBOT
#

property guild_avatar```
Returns an [`Asset`](https://docs.disnake.dev/en/latest/api.html#disnake.Asset "disnake.Asset") for the guild avatar the member has. If unavailable, `None` is returned.

New in version 2.0.
spring flax
#

Or that ^

spring flax
#

Ah then i may be missing context

torn sail
#

Im not sure if this is true but I think display_avatar will return a default pfp if the user doesn’t have one when avatar will return None

slate swan
slate swan
#

!d discord.Member.avatar

#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
slate swan
#

i recommended to use user but she would need to fetch the user since interaction author returns union

spring flax
#

member.avatar returns global no?

torn sail
#

I think it would

slate swan
#

or make a user obj which i forgot how

slate swan
#

!d discord.User.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
slate swan
#

"uploaded avatar"

daring olive
#

i couldn't find a way Skull if one of you do (and confirm it works) pls let me know

slate swan
#

which the member display returns the guild one or the global which she only wants the global

slate swan
sick birch
#

fetching is probably your best bet

slate swan
#

yup

echo wasp
sick birch
#

Not ideal having to make an API request but I don't think there's any other way

slate swan
unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
echo wasp
slate swan
echo wasp
slate swan
#

gave docs because i dont use pymongo but it probably has examplesMarinBonk

echo wasp
native onyx
#

how do i add the desktop in linux debian?

daring olive
#

i'll take a look tmrw thanks guys

#

in the meantime

#

i succeeded at making a cat command

slate swan
daring olive
#

i think this is a win

slate swan
#

i agree02yes

sick birch
native onyx
#

gnome

sick birch
#

From there it's pretty easy to install since it's all modular

#

Easiest way would be to use something like ubuntu that comes with gnome and is debian-based

boreal ravine
slate swan
boreal ravine
slate swan
boreal ravine
#

on_message?

boreal ravine
slate swan
#

you mean if you dm the bot it will just make fun of you im not really sure what you mean

boreal ravine
#

Check if the author of the message is the bot

worldly bane
#

regen the token?

slate swan
#
if message.author == client.user:
    ...

?

boreal ravine
#

sounds like a you problem?

slate swan
#

im so confused rn

hardy yoke
native onyx
#

I tried some tutorials from yt and some websites to solve it, but I was not successful

sick birch
#

But this is more fit for one of the OTs

slate swan
#

just dont compare its idThinkO_O

native onyx
native onyx
#

🧐

slate swan
#

Hi

#

Im back

inner epoch
#

Sheesh I wrote some code and it shouldn't have worked but its working!! Like how😅

jade garden
inner epoch
slate swan
hardy yoke
inner epoch
#

Why dont we have reactions in this channel?

small igloo
#

how to send message when command not found, but also with the command the user invoked, like !testnotfound will return error command "testnotfound" not found, in SO there is a question about that, but i want the one that also send the unknown command, like command {unknown_command} is not found, sorry!

hardy yoke
small igloo
jade garden
worldly bane
small igloo
worldly bane
small igloo
# worldly bane is instance it

idk wym but

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, CommandNotFound):
        not_found = discord.Embed(title="command not found!", description="command not found! might be in progress, "
                                                                          "check `sal! help` for the available "
                                                                          "commands", color=ctx.author.color)
        await ctx.send(embed=not_found)
    raise error```
hardy yoke
#

try commands.CommandNotFound?

jade garden
#

Anyone tell me what's the error?

hardy yoke
#

Although I wouldn't recommend that, it's spammy in servers that use a bunch of diff bots

small igloo
jade garden
worldly bane
small igloo
#

umm what :V

jade garden
hardy yoke
#

You'll have more problems down the line if you continue to use pymongo instead of motor

#

(or sql)

jade garden
worldly bane
hardy yoke
#

Sort of yes but it isn't too different. It's just an async version of pymongo

jade garden
#

Can I use pymongo for now 😩

worldly bane
# small igloo umm what :V
@bot.event
async def on_command_error(ctx, error):
    if isinstance (error, discord.ext.commands.errors.CommandNotFound) is True:
        #do stuff
    else:
        raise error
#

try that

slate swan
#

it would raise a synrax error and no need for true

#

as youre doing if condition

worldly bane
#

I made that when I barely knew any python like 10 months ago 😔

slate swan
worldly bane
#

works anyways

slate swan
small igloo
worldly bane
small igloo
feral jacinth
small igloo
small igloo
# rose birch what are u trying to do?

so when a user invoke a command, and the command unknown (i mean not found) bot will send message "command not found" along with the command the user invoked

worldly bane
worldly bane
small igloo
small igloo
feral jacinth
#

you still have a command context in your hands for this event

#

so you can access the command message through ctx.message

worldly bane
#

^

small igloo
feral jacinth
#

u def didn’t study python to enough level before starting to work with dpy

small igloo
torn sail
#

It will return a Message object

#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
feral jacinth
small igloo
small igloo
# feral jacinth Idk print it to check
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\disnake\client.py", line 515, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\User\Downloads\PycharmProjects\main.py\main.py", line 440, in on_command_error
    print(ctx.message)
  File "C:\Python310\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 116-117: character maps to <undefined>```
```py
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, CommandNotFound):
        not_found = discord.Embed(title="command not found!", description="command not found! might be in progress, "
                                                                          "check `sal! help` for the available "
                                                                          "commands", color=ctx.author.color)
        z = []
        for command in bot.commands:
            print(command)
            print(ctx.message)
            # if similar(ctx.message, command) > 0:
            #     z.append(command)
        not_found.add_field(title="similar commands", description=z)
        await ctx.send(embed=not_found)
    raise error```
vale wing
#

Maybe print ctx.message.content?

small igloo
#

k wait

vale wing
#

And yeah pretty sure ctx.command exists as well

#

!d discord.ext.commands.Context.command

unkempt canyonBOT
unkempt canyonBOT
#

Hey @lone lotus!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

honest shoal
#

hey how can I get a message id?

drowsy thunder
honest shoal
drowsy thunder
#

Then what

#

I am not sure but lemme check

honest shoal
#

I'm making a context menu quote command py async def Quote(inter, message: disnake.Message):

drowsy thunder
#

Hmm

honest shoal
drowsy thunder
#

If your using disnake then i cant help sorry

honest shoal
#

currently this is how the message link looks like py msg_link = f'https://discord.com/channels/{inter.guild.id}/{inter.channel.id}/{???}'

#

and now I'm stuck at what to do with last one

drowsy thunder
#

Hm

honest shoal
worldly bane
honest shoal
#

I haven't tried yet

worldly bane
unkempt canyonBOT
drowsy thunder
#

@maiden fable help him

maiden fable
#

With?

drowsy thunder
#

This dude

sharp lintel
#

Message link is always py https://discord.com/channels/server_id/channel_id/message_id

maiden fable
#

Yea

worldly bane
#

Yea

drowsy thunder
#

@honest shoal help him

#

I mean

honest shoal
#

let me test with message.id

drowsy thunder
#

@honest shoalor help

worldly bane
#

🗿

maiden fable
#

@drowsy thunder Stop pinging randoms please

tawdry perch
#

this .

maiden fable
#

We ain't liable to help anyone here

honest shoal
#

how can I get the timestamp of a selected message?

maiden fable
#

!d discord.Message.created_at

unkempt canyonBOT
drowsy thunder
#

Sorry my discord is glitching

slate swan
#

👋

unkempt canyonBOT
#

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

drowsy thunder
#

Sorry my discord is glitching

#

Oof

#

Finally restarted discord

slate swan
#

.

#

how to send a welcome message through the dc bot

maiden fable
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

member*

drowsy thunder
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

memer

maiden fable
#

😔 Stop

honest shoal
boreal ravine
sharp lintel
#

But generally it's always 3 things to know where the message is

honest shoal
drowsy thunder
#

Guys how to make a eval command

#

Like

worldly bane
drowsy thunder
#

!e

print(1+1)
unkempt canyonBOT
#

@drowsy thunder :white_check_mark: Your eval job has completed with return code 0.

2
maiden fable
drowsy thunder
honest shoal
#

use jishaku

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](https://docs.python.org/3/reference/toplevel_components.html#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`.
slate swan
#

bot?

#

weird

honest shoal
#
AttributeError: type object 'datetime.datetime' has no attribute 'message'
worldly bane
honest shoal
#

💀

worldly bane
#

🗿

honest shoal
#

!d disnake.Message.created_at

unkempt canyonBOT
honest shoal
#

how can I make a timestamp from this?

slate swan
#

#bot-commands

worldly bane
drowsy thunder
honest shoal
#

no, the embed timestamp

boreal ravine
drowsy thunder
#

!d nextcord.Embed

unkempt canyonBOT
#

class nextcord.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.10)") 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://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed.Empty "nextcord.Embed.Empty").

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

See

#

Timestamp

#

!d disnake.Embed

unkempt canyonBOT
#

class disnake.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.10)") 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://docs.disnake.dev/en/latest/api.html#disnake.Embed.Empty "disnake.Embed.Empty").

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

See the last part?

boreal ravine
honest shoal
drowsy thunder
drowsy thunder
#

Use that

slate swan
#

how to get messages of a member?

drowsy thunder
drowsy thunder
slate swan
#

like how many msg i did

honest shoal
# drowsy thunder Use this

I know how to set a timestamp in embeds, I was asking about the timestamp of specific message which was created in past

drowsy thunder
slate swan
#

count

drowsy thunder
sharp lintel
# drowsy thunder Use this

@slate swan TextChannel has a .history() you can use, but you will have to loop over every TextChannel of a server

slate swan
#

bro

sharp lintel
#

Whops I replied to wrong message

slate swan
#

.

worldly bane
slate swan
#

ok.

honest shoal
#

yes this is working fine

drowsy thunder
#

Sorry

slate swan
drowsy thunder
sharp lintel
#

Unfortunately you need to do some API call for discord to return them messages to you

#

So unless you are storing discord messages

boreal ravine
slate swan
drowsy thunder
#

I have a idea

drowsy thunder
#

Using a data base and a @client.listen event

sharp lintel
maiden fable
drowsy thunder
#

So on_message it will add the count to the database

slate swan
#

docs pls?

maiden fable
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

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

Examples

Usage...
slate swan
#

ok

slate swan
drowsy thunder
slate swan
#

If yk wut i mean

#
          count = 0
          for channel in ctx.guild.channels:
               for message in channel.history():
                    if message.author == user:
                         count += 1
```didnt test yet
honest shoal
honest shoal
#

which will be wiped after every restart

slate swan
#

yes

slate swan
drowsy thunder
#

@maiden fable check ur dms

slate swan
#

idk why my file are getting that M

boreal ravine
#

m = modified

honest shoal
slate swan
#

it auto update the files?

drowsy thunder
#

Guys,can someone check my repl,it has a error i cant even fix

honest shoal
#

send the error

boreal ravine
slate swan
#

okay

#

it say this stuff is not saved

#

in ur repo

slate swan
#

like this

boreal ravine
#

ok

slate swan
#

so

#

how to

drowsy thunder
#

@slate swan yo can yo help me as the error Im getting is almost impossible to fix if you dont freaking delete the code

slate swan
#

can i reupload from vsc

drowsy thunder
#

Check the repl.you will regonize it

slate swan
#

can u share here

drowsy thunder
#

It will be bad,I will dm

slate swan
unkempt canyonBOT
#

Pasting large amounts of code

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

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

honest shoal
#

use paste bin

drowsy thunder
#

No,the code is a app-issue

#

I will dm the replit link,and can ya fix it

#

Its a minor problem but i cant fix it.

slate swan
#

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'HistoryIterator' object is not iterable

slate swan
#

for message in channel.history():

boreal ravine
#

it's an awaitable

slate swan
#

ok

drowsy thunder
#

Can I dm you replit link @slate swan

slate swan
#

async for message in channel.history():

drowsy thunder
#

Someone help me

boreal ravine
#

do ```py
async for message in channel.history():
...

drowsy thunder
#

AAAAAAAAAAAAAAAAA

hardy yoke
#

and or the error

#

otherwise no

drowsy thunder
boreal ravine
hardy yoke
#

The only option you've given us so far is to rub a crystal ball and make a guess

drowsy thunder
#

honestly the IDE is replit so its normal to have billions of issues LOL

hardy yoke
#

If it's on repl perhaps try joining their discord server

native onyx
drowsy thunder
#

But the error is a bit like this

honest shoal
#

!indent

maiden fable
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

for channel in ctx.guild.channels:

#

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'CategoryChannel' object has no attribute 'history'

drowsy thunder
#

@maiden fable can you check it cuz I tried many times and didnt work

native onyx
#

why don't you use vscode?

slate swan
#

i do

drowsy thunder
boreal ravine
drowsy thunder
#

But how the FUCK can I fix my error

#

aaaaaaaaaaaaaaaaaaaaa

prisma spoke
#

fix the indents

slate swan
#

for channel in ctx.guild.channels:

#

?

drowsy thunder
slate swan
drowsy thunder
prisma spoke
#

in other words or simple words fix the spaces and tabs used

slate swan
#

why u using replit but

slate swan
prisma spoke
#
@bot.command()
async def fm(ctx, channel: nextcord.TextChannel=None):
    channel = channel or ctx.channel
    messages = await channel.history(oldest_first=True,limit=1).flatten()
    await ctx.send(messages[0])```

this ^^ prints: ```py
<Message id=862529724579315733 channel=<TextChannel id=843120245908176898 name='general' position=0 nsfw=False news=False category_id=843120245908176897> type=<MessageType.default: 0> author=<User id=806458860662816825 name='Shadow' discriminator='9430' bot=False> flags=<MessageFlags value=0>>```

now how do i get the message id from this
#

i am unable to iterate thro the printed msg cuz 'message object isnt iterable

prisma spoke
boreal ravine
boreal ravine
supple thorn
slate swan
#
giveaway_options = [
            discord.Option(str, name = "giveaway_type", required = True, description = "Choose a giveaway type.",
                choices = [
                    discord.OptionChoice(name = "Button"),
                    discord.OptionChoice(name = "Reaction")
                ]),
            discord.Option(discord.TextChannel, name = "channel", default = None, description = "Choose a channel."),
            discord.Option(discord.Member, name = "hosted_by", default = None, description = "Choose a member."),
            discord.Option(int, name = "winners", default = 1, description = "How many winners should it be?", min_value = 1, max_value = 30),
            discord.Option(discord.Role, name = "ping_role", default = None, description = "Choose a role that should get pinged.")
]
```gives an error saying ` ClientException: Too many arguments passed to the options kwarg.`
slate swan
boreal ravine
#

and maybe read the error, it can't have that many options

slate swan
slate swan
small igloo
prisma spoke
prisma spoke
prisma spoke
boreal ravine
hasty pawn
#

????

boreal ravine
#

messages[0].author.id

prisma spoke
#

oh wait yea

hasty pawn
#

lmao

slate swan
#

hu'

prisma spoke
prisma spoke
hasty pawn
#

ohhh nvm i see now

prisma spoke
#

i mean yes but i dont need that

slate swan
boreal ravine
prisma spoke
boreal ravine
#

Youtube, docs

slate swan
#

Is it possible to send
Embed inside button interaction response?
If yes please explain

#

I mean
The bot should send a embed
On button click
Not saying that embed inside a button or button inside embed

lyric tusk
#

how can i make is so only open works

@client.command()
async def knock(ctx):
    def check(message):
        return message.author == ctx.author and message.channel == ctx.channel

    embedk = nextcord.Embed(title="Somone is knocking on the door", description="type open to open the door")
    await ctx.send(embed=embedk)
        
    desc = await client.wait_for('message', check=check)


    embed = nextcord.Embed(description=desc.content, color=0xFFFF)
    await ctx.send(embed=embed)
slate swan
#

Sure

#

Yea but
That would require embed in variable,
I tried doing it but upon clicking the button nothing pops

#

um-
I’ll just dm you something
And send the code later

lyric tusk
#

ok

slate swan
#

Not on my lap Rn
Sorry

lyric tusk
#

ty

hasty pawn
#

nextcord is just a bad fork tbh

honest shoal
#

disnake is nice

#

or just go back to dpy

hasty pawn
#

thats what i did

placid skiff
#

I tried something like 3-4 forks, included nextcord and Pycord, but disnake indeed is the best fork i've ever tried

heavy folio
#

dpy best

steep estuary
#

i am working with heroku, it is giving ffmpeg not found error how can i solve this ?

heavy folio
#

nextcord pycord 👎

steep estuary
#

but how i can do that with heroku ?

placid skiff
#

.

fresh iron
#
async def on_ready():
  await client.change_presence(status=discord.Status.online, activity=discord.Game("TESTING"))
``` how do i make the discord.game nothing at all
spring flax
placid skiff
placid skiff
# fresh iron ```py async def on_ready(): await client.change_presence(status=discord.Status...
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))

# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))

# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))

# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))
spring flax
#

Instead set the activity and status kwargs in the constructor of bot. py bot = commands.Bot(command_prefix="something", activity=..., status=...)

rose birch
#

sup folks, not to barge into the current issue but I need some advice on how to do things. I have a price tracker where if several items dips below a threshold, it will send a message on discord.
currently that is hardcoded in with bot.loop.create_task(tracker(itemName, threshold)) but I want to be able to use !create tracker itemName to dynamically spin up new tasks. issue is, I'm not sure the correct implementation of this

#

creating the ! commands is not my issue, more so is there any best practices for spinning up new tasks to track new items/deleting specific tasks when I don't want to track the items anymore

placid skiff
#

uhm so essentially you want to delete a tracker? where those tracker are saved?

rose birch
dense swallow
#
    async def get_logs_channel(self, guild_id):
        data = await self.bot.db.fetchval("SELECT channel_id FROM modlogs WHERE guild_id=$1", guild_id)
        if data:
            return self.bot.get_channel(data)

    async def create_webhook(self, guild_id):
        channel = await self.get_logs_channel(guild_id)
        return await channel.create_webhook(
            name=f"{self.bot.user.name} " + "Logging",
            avatar=self.bot.user.avatar.url,
            reason="For logging"
        )
```  'NoneType' object has no attribute 'create_webhook'
#

how do i fix this? when sending to that channel, it doesnt give me this error.. but when im trying to create a webhook it shows me this error

junior verge
#

What does this mean?

quick gust
#

show ur json file

junior verge
#
{}
quick gust
#

yeah it has to be


}``` iirc
junior verge
#

Just that?

#

Save and run?

quick gust
#

sure, try

placid skiff
dense swallow
rose birch
placid skiff
#

And do you want to stop it or cancel it?

rose birch
#

are they not effectively the same thing?

junior verge
#

Want my code?

rose birch
#

I'm not sure what the difference but perhaps I want to completely stop the task

quick gust
# junior verge

no, its simple, there's just no data for that guild in the json file

quick gust
#

exactly

unkempt canyonBOT
#

cancel(msg=None)```
Request the Task to be cancelled.

This arranges for a [`CancelledError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.CancelledError "asyncio.CancelledError") exception to be thrown into the wrapped coroutine on the next cycle of the event loop.

The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) … … `except CancelledError` … [`finally`](https://docs.python.org/3/reference/compound_stmts.html#finally) block. Therefore, unlike [`Future.cancel()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel "asyncio.Future.cancel"), [`Task.cancel()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel "asyncio.Task.cancel") does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.

Changed in version 3.9: Added the *msg* parameter.

The following example illustrates how coroutines can intercept the cancellation request:
quick gust
#

there needs to be data for you to return

junior verge
#

so how to fix that uh?

quick gust
#

you add data lol

#

manually or through a command

#

if u wanna do it for a setprefix command

junior verge
#

yeah nvm

#

dw

quick gust
#

also I'd suggest using databases

boreal ravine
dense swallow
#
webhook = await self.create_webhook(before.guild.id)
await webhook.send(embed=em)
#

@boreal ravine ^^

boreal ravine
#

self is none Hmm_HD

dense swallow
#

its used in cogs

dense swallow
#

when converting to webhook, it gives me this error

placid skiff
#

Cog class has no method create_webhook .-.
get_logs_channel could be something declared somewhere

azure scroll
#

how to mention a voice channel?

cloud dawn
placid skiff
#

!d discord.VoiceChannel.mention

unkempt canyonBOT
heavy radish
#

Just curious. If I am using multiple files for code. Is it better to use COGs or to just from file import file. And whatever your answer is, what's the benefit of it

#

Brb

junior verge
#

no module named nextcord

#

How is that possible?

slate swan
#

If you're on phone you'll see something like #channelname

junior verge
slate swan
junior verge
junior verge
#

You mean like install it

slate swan
#
utc_time = calendar.timegm(date.utctimetuple())+1800
print(utc_time)```

this is my code
i want it to print 1800 more seconds from current time
junior verge
#

Uh okay

slate swan
#

Idkia_think_thonk PB_lmao_sweat

junior verge
#

Well my code is on heroku so it should work

west juniper
#

somebody help

junior verge
#

Doesn't have anything to do with my ide

slate swan
#

Then add "nextcord" to ur requierements.txt file

junior verge
#

aahhhh

slate swan
#

oh god i cant spell

junior verge
#

yeah thats prob it

supple thorn
junior verge
#

ty bro

slate swan
#

Yw

unkempt canyonBOT
junior verge
#

I saw with nextcord you always need like a testserverid for slash commands, do you really need that? Aren't you able to just get slashcommands without that

slate swan
rose birch
# placid skiff !d asyncio.Task.cancel

so I dug into it for a little while and had almost got what I wanted(cheers). I renamed my task to SPAM for clarity and was able to list out all my tasks with currentTasks = asyncio.all_tasks() then printing that out. now I'm stuck, how do I cancel the SPAM task with the object given in currentTasks?

<Task pending name='SPAM' coro=<spamTest() running at c:\scripts\marketNotifier\marketNotifierDiscord.py:187> wait_for=<Future pending cb=[Task.task_wakeup()]> cb=[_ClientEventTask.task_wakeup()]> 
....
....
slate swan
#

Correct me if im wrong down_syndromesmile

hoary cargo
#

^

junior verge
#

Can I just remove aiohttp?

hoary cargo
#

bruh

#

why you have dpy, disnake and nextcord

#

all together

junior verge
#

nextcord is not even in my requrements.txt

slate swan
slate swan
junior verge
#

I removed disnake

hoary cargo
junior verge
hoary cargo
#

i don't get it why you installed all 3 in the first place lol

junior verge
#

alright uninstalled

junior verge
hoary cargo
#

MR_canny_meh_stage keep just one, preferably disnake

junior verge
#

I just want to get slash commands man

#

its just not working for me sad

#

and I don't get it

slate swan
junior verge
#

Yeah but I just don't understand it with like the testserver ID etc

junior verge
slate swan
#

1h (or maybe less) for global idk

junior verge
#

What

#

Like imagine I do all the disnake stuff and don't include the test id server then I can instantly just see the slash command and test it

steep estuary
#

I am Getting this error of youtube-dl how to solve this?

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)
tawdry perch
#

we can't help you on that @steep estuary

steep estuary
#

hm ohk

#

i want to add music in my discord bot and i am not getting any way

tawdry perch
#

can't help on that ¯_(ツ)_/¯

dull terrace
#

anyone have tips on emoji uploads

#

always seem to come out blurry

#

best format to upload in?

slate swan
#

Goodmorningthanks

dull terrace
#

morning

#

looks like discord uses webp, but you can't upload webp directly 😤

uncut comet
#

hey im using discord py v2 how can i use a on message delete in a cog

maiden fable
uncut comet
#

thanks

slate swan
#

!d discord.on_message_delete

slate swan
slate swan
#

you said add self argument if in a class when a Cog is a subclassAG_ChikaStunned

maiden fable
#

Wow never knew

placid skiff
maiden fable
placid skiff
#

F

gritty dust
#
@bot.command()
@commands.has_permissions(kick_members=True, administrator=True)
async def kick(ctx,*, ma: discord.Member, reason=None):
    try:
        await ctx.guild.kick(ma)
        await ctx.send("Done!")
    except:
        ctx.send("Please mention the member you want to kick")
discord.ext.commands.errors.MissingRequiredArgument: ma is a required argument that is missing.

HELP please fix it if you can

visual island
#

firstly, you cant catch MissingRequiredArgument exception with a try-except

maiden fable
#

Only one kwarg allowed

gritty dust
maiden fable
#

Only one arg after *

jade meadow
#

how do i make it send a message in the discord channel once it has connected

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')
final iron
#

on_ready isn't called when you connect to the api

#

!d discord.on_connect

unkempt canyonBOT
#

discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") for that.

The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") also apply.
jade meadow
#

oh

#

thats why the bots not working

final iron
#

Perhaps

jade meadow
#

can you find what i'm doing wrong? im trying to follow a tutorial but the bot isn't working.

import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv("DISCORD_GUILD")


client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

  

@client.event
async def on_message(message):
    if 'test' in message.content.lower():
        await message.channel.send('test')


client.run(TOKEN)
maiden fable
#

Error?

#

@jade meadow

dull terrace
#

even though discord downscales your emojis apparently you need to upload in 128x128 to get non blurry ones

jade meadow
slate swan
jade meadow
slate swan
#

theyre both events but trigger in different circumstances

spring flax
#

can the colored text be used in bot embeds? The ainsi

maiden fable
#

Yea

slate swan
#

but yes if we are talking about when the bot connects to the gateway its on_connect

spring flax
maiden fable
slate swan
#

no it is iirc theyre just missing some colors

spring flax
#

i'm on pc

maiden fable
#

And it doesn't work?

spring flax
#

no

#

i am copying the example in the pins

#
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
#

is it colored for anyone else?

slate swan
#

nope

spring flax
#

huh...weird

slate swan
#

👋

spring flax
#

maybe what i inputted was wrong then

slate swan
#

is it in a ansi code block?

spring flax
maiden fable
#
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
#

Still doesn't work?

spring flax
#

nope

slate swan
#

no

spring flax
slate swan
#

Whats that

maiden fable
#

Then yea, it doesn't work for everyone

slate swan
#

:<

#

Colored text cool

west juniper
#

@client.command() async def eval(ctx, input:str): result = eval(input) result2 = result type1 = type(result) await ctx.send(f"```{result2}```\n```{type1}```")

#

any prob in my code?

maiden fable
#

Yes

west juniper
maiden fable
#

!d exec is what u should use

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](https://docs.python.org/3/reference/toplevel_components.html#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`.
west juniper
#

@maiden fable is this what i am suposed to do?

jade meadow
#

can someone explain the error for this to me?

import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.environ['DISCORD_TOKEN']
GUILD = os.environ['DISCORD_GUILD']

error:

Traceback (most recent call last):
  File "bot.py", line 9, in <module>
    GUILD = os.environ['DISCORD_GUILD']
  File "/nix/store/xd5m4hym6gjmdfl0hx1xpj4j2hlc54xx-python3-3.8.12/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'DISCORD_GUILD'
static beacon
jade meadow
prisma spoke
static beacon
slim ibex
#

What reasons 🗿

prisma spoke
#

repl is bad

jade meadow
slim ibex
#

There is no reason to use it over VSCode or other ide

prisma spoke
static beacon
# prisma spoke repl is bad

unless you want to pursue coding but you dont have the right tools (like a windows / linux operating system)

#

even macos

slim ibex
#

I have all kinds of programming shit in my school computer

gaunt ice
prisma spoke
static beacon
#

just not chromebook

slim ibex
#

Python, Rust, .NET, VS, VSCode, etc

jade meadow
static beacon
jade meadow
#

its only using my magic powers i found how to acess discord

jade meadow
slim ibex
#

ask for an admin password?

static beacon
prisma spoke
static beacon
#

the amount of times ive used kill 1 is just incredible

jade meadow
#

i replaced the env in the program with the actual values, and there are no more errors but the program still doesnt work

#
# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = there is something here dw about it
GUILD = 'headspace'


client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

  

@client.event
async def on_message(message):
    if 'test' in message.content.lower():
        await message.channel.send('test')


client.run(TOKEN)
#

when i send test

#

its supposed to say test

#

as well

#

but nothing happens

#

what

#

what was that reply

supple thorn
#

Dw about it

jade meadow
#

why delete

supple thorn
#

So you don't see

static beacon
#

client.run(os.environ['token'])

#

no need for the variable

supple thorn
azure scroll
#

what are "scopes" in discord dev portal?

jade meadow
#

its not printing anything

supple thorn
jade meadow
#

yes

supple thorn
#

Why don't you click the run button

#

That's why

static beacon
#

and run

jade meadow
static beacon
#

or use a .replit file

#

and make run="python bot.py" if you want

supple thorn
supple thorn
#

Cracks typing a college essay

#

Im outtie

jade meadow
#

still nothing

hushed galleon
jade meadow