#discord-bots

1 messages · Page 223 of 1

vocal snow
#

"path/to/my/image.png" is the filepath of your file

vocal snow
#

what nope

slate swan
vocal snow
#

...

#

I know it's not

slate swan
#

so?

vocal snow
#

I'm saying you have to change it

slate swan
vocal snow
#

what part about it do you not understand

#

just change the filename

slate swan
vocal snow
#

please read the article

slate swan
slate swan
vocal snow
#

everything is very clearly described there

slate swan
slate swan
vocal snow
#

To do so, upload the image normally with abc.Messageable.send(), and set the embed’s image URL to attachment://image.png, where image.png is the filename of the image you will send.

slate swan
#

ic

vocal snow
#

I repeated verbatim from the article

#

what part of that is unclear

slate swan
#

verbatim means?

vocal snow
#

i copied it exactly as it was written in the article

slate swan
#

sry

#

file = discord.File("C:\Users\Dell\Downloads\FotoJet(1).png", filename="FotoJet(1).png")

#

its showing error here

#

@vocal snow

vocal snow
#

escape your backslashes

#

or use a raw string literal

slate swan
#

@vocal snownow the whole command is not working oof

slate swan
#

....

#

sir

vocal snow
#

what?

slate swan
vocal snow
#

Presumably it's ignoring an exception raised in on_message

slate swan
#

heh?

vocal snow
#

do you know what an Exception is?

slate swan
naive briar
#

Doesn't seem like it

vocal snow
#

right, well I'm not going to be able to help you further

slate swan
vocal snow
#

knowing python basics is an unfortunate prerequisite of discord.py

slate swan
#

i really want to learn help sir

vocal snow
#

!resources

unkempt canyonBOT
#
Resources

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

vocal snow
#

lots of free books and resources to learn basic python

slate swan
vocal snow
#

which book/course did you do?

#

Seems like you must've skipped quite a lot

slate swan
naive briar
#

That explains it

vocal snow
#

that would do it

slate swan
#

heh?

lyric halo
#

hi guys what's up

lyric halo
#

what

slate swan
#

its not general tho

lyric halo
#

hmm ur right my bad

slate swan
#

Oof it sucks

slate swan
#

...

#

..

#

.

#

@slate swansay yes or no wen

#

with?

slate swan
# slate swan with?

file = discord.File("C:\Users\Dell\Downloads\FotoJet(1).png", filename="FotoJet(1).png")
its showing error here

slate swan
#

it could not find image

#

your path is wrong

slate swan
naive briar
#

The error doesn't lie

slate swan
#

copy pasted what

#

copy as path

#

try moving the image to your project directory and using relative path

#

ok

mighty sun
#

hello all, @limpid holly beware, he asks for money, pretends to code and then scams you

vocal snow
mighty sun
#

yes..

#

I can't do it. 😦

slate swan
slate swan
mighty sun
#

30..

slate swan
#

30 dollars?

mighty sun
#

yes

#

it relieves me I find to help me... 😦

slate swan
#

bruhh

slate swan
#

use intents

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

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

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

slate swan
#

see this

slate swan
# slate swan use intents
async def banner(ctx, Member: discord.Member):
  banner_url = User.banner.url
  if banner.url:
    await ctx.send(User.banner.url)
  else:
    await ctx.send("This user does not have a banner.")```
#

could you help me

slate swan
#

okay

slate swan
slate swan
slate swan
#

89

slate swan
#

'-'

slate swan
slate swan
slate swan
slate swan
#

bruh

slate swan
#

what did you change in code

slate swan
#

show updated code

#
async def banner(ctx, User: discord.User):
  banner_url = User.banner.url
  if banner.url:
    await ctx.send(User.banner.url)
  else:
    await ctx.send("This user does not have a banner.")```
#

okay first of all you define varriable banner_url right?

slate swan
#

but then you dont use it you do something like banner.url which does not exist

#

. . .

#

use the varriable you defined

#

Ok wait

slate swan
# slate swan use the varriable you defined

Ignoring exception in command banner:
Traceback (most recent call last):
File "/home/runner/FloralwhiteValuableStringweres/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 81, in banner
banner_url = User.banner_url
AttributeError: 'Member' object has no attribute 'banner_url'

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

Traceback (most recent call last):
File "/home/runner/FloralwhiteValuableStringweres/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/FloralwhiteValuableStringweres/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/FloralwhiteValuableStringweres/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'banner_url'

mighty sun
#

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

slate swan
#

!d discord.Member

unkempt canyonBOT
#

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

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/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/latest/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/latest/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.
slate swan
#

the User.banner.url is good

#

wha

#

but your if condition is wrong

#
async def banner(ctx, User: discord.User):
  banner_url = User.banner_url
  if banner.url:
    await ctx.send(User.banner_url)
  else:
    await ctx.send("This user does not have a banner.")```
#

like this?

#

no i just said

#

User.banner.url is correct

#

but then in your if condition use varriable you define

#

u r using both bot and client why tho??

#

aaaaaa

#

read the error they even gave you a link to follow

#
async def banner(ctx, User: discord.User):
  banner_url = User.banner.url
  if User.banner_url:
    await ctx.send(User.banner.url)
  else:
    await ctx.send("This user does not have a banner.")```
#

no

#

you define varriable banner_url not User.banner_url

#

no, not at all

#

nope

#

u are hopping on bot too early

#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

read this ig

#
async def banner(ctx, User: discord.User):
  banner_url = banner_url
  if User.banner_url:
    await ctx.send(User.banner.url)
  else:
    await ctx.send("This user does not have a banner.")```
#

yo like this??

slate swan
#

if no the discord bot is not the best project for the first one

slate swan
slate swan
#

to read

#

oh

slate swan
unkempt canyonBOT
#
Resources

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

slate swan
#

wht is tht basic knowledge??

#

if u r thinking only knowing wht is int and str is enough then u r wrong

#

lol same here

#

learn pyhton

#

i know both python and c# and there is a lot between those 2 languages

#

ya lol

slate swan
#

@slate swanisnt this is how path looks like?

slate swan
slate swan
#

from photo

vague zephyr
slate swan
#

No such file or directory: 'C:\Users\Dell\Downloads\FotoJet(1).png'
wht this tho

slate swan
#

means that there is no such file

slate swan
vague zephyr
#

that file doesn't exist

#

go into your downloads folder

#

and see for yourself

#

if it exists or not

slate swan
vague zephyr
#

well then good for you

slate swan
#

but now the embed not showing only picture is visible

slate swan
#

....

#

@vague zephyris tht aki in ur pfp?

vague zephyr
#

idk

slate swan
#

heh?

vague zephyr
#

my friends just told me to put it

slate swan
#

ic

#

thts an anime charachter

vague zephyr
#

i think it's from chainsaw man or something idk

slate swan
#

@slate swan

#

anyone help?

#

anyone help

#

What

#

my embed message is not been shown

#

becz i embeded an image

#

now tht image covered it whole

#

but commands are working

#

.

#

@slate swan

#

Ur token is none

#

Try printing it , will return none

slate swan
slate swan
#

of code?

#

Of what u get

#

i mean the embed

#

one sec

#

Already told you

#
async def test(self, inter, hey: Option(str, choices=['one', 'two', 'three'])):```
how can i provide some context to the options
#

@slate swanur code is diffrent then

#

Ur token is none bro

#

enter toke in client.run

#

💀

#

Don’t share token

slate swan
#

Remove os.getenv

#

Not for you

#

send it in client.run tho

slate swan
#

thats not how to use env varriables

unkempt canyonBOT
#
Using .env files in Python

.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.

Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.

In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:

TOKEN=a00418c85bff087b49f23923efe40aa5

Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:

from dotenv import load_dotenv()

load_dotenv(".env")

The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:

from os import getenv

my_token = getenv("TOKEN")

For further reading about tokens and secrets, please read this explanation.

slate swan
slate swan
#

by the image

#

i dont know env var either

slate swan
slate swan
#

Ikr

#

it was supposed to be like this then the image at the end

#

wait am i supposed to use footer?

#

Ye..

#

ic

#

Try?

#

sry for wasting ur time

slate swan
#
async def test(self, inter, hey: Option(str, choices=['one', 'two', 'three'])):```
how can i provide some context to the options
slate swan
#

it's pycord

#

out of my reach sry

#

okey

slate swan
slate swan
slate swan
#

but caan i get hep pls?

#

?

#

help*

slate swan
#

!d discord.Embed.footer

unkempt canyonBOT
#

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

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

If the attribute has no value then `None` is returned.
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

show code then

slate swan
#

also you override your embed creating a new one

slate swan
#

no when sending

#

file = file?

#

yes

#

i have to remove tht?

#

in docs it was given so i did

#

!d discord.abc.Messageable.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/latest/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.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

you pass file when you want to send image if you want to add it to embed you do embed.set_image()

slate swan
#

in third last line

#

now its like this oof

slate swan
#

the file=file was correct

#

ic

#

but then it will remain same again like tht so wht is wrong in the code??

#

you override embed

slate swan
#

yes you redefine it

slate swan
#

u mean by embed = discord.embed()

#

yes

#

??

#

ic

#

you straight copied it from the docs and dont know what it does to code

#

remove this line

young pendant
#

Hey Guys
Is there any way, I can run this script (obviously with renamed variables and commands) multiple times? https://paste.pythondiscord.com/aninahoveq
For example.
I would like to run that script through my bot.
But what do I need to do, to run 2 or 3 of these scripts?

slate swan
#

@slate swanbut the image is too big how can i make it small can i write code for like resize or smth??

slate swan
#

but there are a few ways to attatch image to embed

#

image is the biggest one

slate swan
#

you can use thumbnail but then it will be located on the top right

#

if i want it at bottom?

#

footer?

#

then you need to use image

#

footer will be just a small icon

#

as you see in image

slate swan
#

riight?

#

you can try changing size of image you have locally but i dont know if it will change something

slate swan
slate swan
#

wait

#

i am sending one ss

#

how can i do like this??

#

..

#

wht is the * in the code?

#

in what code

#

set_thumbnail(*, url)

#

here?

#

and from where did you get it

slate swan
slate swan
slate swan
#

params?

#

parameters?

#

yes

#

the * in this indicates that all parameters after are keyword only

slate swan
#

like this

#

ig

#

so you cant do embed.set_thumbnail("some url") you need to do embed.set_thumbnail(url="some url")

slate swan
slate swan
slate swan
slate swan
#

no idea

#

ic

young pendant
#

I would like to have that feature maybe 3-4 times

left dew
#

am i allowed to ask a question about a bitcoin transaction confirmation checker?

uneven hearth
#

how can i create collapsible messages?

glad cradle
#

wdym? do you mean ephemeral messages?

slate swan
#

how can i keep my image under the embed

#

??

#

is ubuntu better as a vps than windows

thin raft
#

in the vast majority of cases yeah

thin raft
thin raft
unkempt canyonBOT
#
slate swan
slate swan
#

like this?

#

@thin raft

thin raft
#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

probably didn't did that

slate swan
#

.

thin raft
slate swan
#

i have used the set_image comand but in this code i wrote humbnail

slate swan
thin raft
#

u are confusing me

slate swan
#

sry

thin raft
#

you ask how to do something, I tell you how to do it

#

and you use another method

slate swan
slate swan
thin raft
#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

embed.set_thumbnail(url="attachment://FotoJet(1).png")

#

embed.set_image(url="attachment://FotoJet(1).png")

thin raft
#

?

slate swan
#

i have to do this right?

thin raft
#

try it and see

slate swan
#

its same

thin raft
#

you aint doing something right

#

embed.set_image

slate swan
thin raft
#

sets the image

#

you didn't, computers do not get confused

slate swan
#

i did this

thin raft
#

you are checking for different images

#

FotoJet (1).png

#

name the image right

glad cradle
#

oof why set_image isn't accepting a file kwarg in d.py

slate swan
#

thts its name

#

the output i get

#

@thin raftsry for disturbance

slate swan
glad cradle
#

mmm didn't you have to put the full Path to the file instead of a name?

thin raft
#

message.channel.send(file = file, ...)

glad cradle
thin raft
#

it will send the file :o

slate swan
glad cradle
#

sigh let me check disnake internals

uneven hearth
# thin raft wdym by that x2

hm, you know when you send a long code/message, discord automatically changes it into some sort of a file, that's what i meant

slate swan
#

it c: thing there ig

young pendant
uneven hearth
thin raft
slate swan
young pendant
thin raft
young pendant
#

i saw that site, but I'm to stupid to understand that

thin raft
#

Then I think you should get better at python

#

dw it's a common thing, it also happened to me

slate swan
#

u mean right?

#

..

thin raft
#

name the file right first

slate swan
#

@thin raft

thin raft
#

name the file right

#

remove the (1)

slate swan
#

but there is a flie name if i remove the 1

#

like it was renamed

thin raft
#

name them correctly

#

or have you seen twins called Jake and Jake1

slate swan
#

ic

slate swan
#

??

glad cradle
#

try with attachment://yourfilepathhere

slate swan
#

but in docs it says path

#

oof

glad cradle
#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

path/to/my/image.png

glad cradle
#

ah then it should work

slate swan
#

but it is not

#

working

glad cradle
#

mm

slate swan
slate swan
thin raft
#

it's like wondering why "9aghdpañowu0g`0.png" is written wrong

slate swan
#

lol sry

thin raft
#

nah dw

slate swan
#

so r we not supposed to use number in .png??

glad cradle
#

btw why d.py always choose discutibile designs

thin raft
#

ur suposed to name things right

slate swan
thin raft
slate swan
thin raft
#

sqlite or mysql depending on the project

slate swan
glad cradle
#

yeah but why it require the user to build the url manually when it could be done without much pain by the lib

thin raft
#

you can use relative path iirc

slate swan
glad cradle
thin raft
#

how big it needs to be and if I need more than 1 connection at a time

slate swan
thin raft
#

reppel?

glad cradle
#

replit

thin raft
#

I have my own dedicated server

#

replit 💀

slate swan
thin raft
#

not that

hushed galleon
left dew
#

await cembed.delete()
error: AttributeError: 'Embed' object has no attribute 'delete'

thin raft
#

check this

slate swan
thin raft
#

yeah

unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

hushed galleon
thin raft
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, 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.

x == y Checks if two embeds are equal.

New in version 2.0...
left dew
hushed galleon
#

as in you have a message with an embed, and you want to only remove the embed?

left dew
#

no, its just an embed

#

i just want to delete the embed

glad cradle
thin raft
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

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

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
thin raft
#

then set supress to True

#

message.edit(supress = True)

left dew
#

what does that do

thin raft
#

will remove the embeds

hushed galleon
left dew
#

that is my embed

#

and i want to delete it

thin raft
#

message.delete

left dew
#

delete the message

hushed galleon
glad cradle
#

it requires some discord.Embed and discord.File rewrite

#

and it should be edited for other things too, to be consistent

#

this is how it's actually implemented in disnake

hushed galleon
#

does it? i would imagine storing the files as an attribute of embed then having the send() method extract those files to be uploaded

#

by coupling i just mean that an embed is basically a JSON object with some string values so it doesnt make sense to make it responsible for file objects

glad cradle
unkempt canyonBOT
#

disnake/embeds.py lines 828 to 832

if file:
    if file.filename is None:
        raise TypeError("File must have a filename")
    self._files[key] = file
    return f"attachment://{file.filename}"```
`disnake/abc.py` lines 1599 to 1602
```py
for embed in embeds:
    if embed._files:
        files = files or []
        files.extend(embed._files.values())```
hushed galleon
glad cradle
#

no file handling is not that different between d.py and disnake

young dagger
#

How can I make this task to start every third day at 00:00 am?

@tasks.loop(hours=24 * 3)
async def update_elo_ratings():```
thin raft
# young dagger How can I make this task to start every third day at 00:00 am? ```python @tasks...
import datetime
from discord.ext import commands, tasks

utc = datetime.timezone.utc

# If no tzinfo is given then UTC is assumed.
times = [
    datetime.time(hour=8, tzinfo=utc),
    datetime.time(hour=12, minute=30, tzinfo=utc),
    datetime.time(hour=16, minute=40, second=30, tzinfo=utc)
]

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.my_task.start()

    def cog_unload(self):
        self.my_task.cancel()

    @tasks.loop(time=times)
    async def my_task(self):
        print("My task is running!")```
young dagger
hushed galleon
hushed galleon
#

afterwards dpy will keep it synced to the correct interval

young dagger
hushed galleon
#

what akex said, start_time doesnt exist

blissful badge
#

does anyone know if the current discord.py functionality supports publishing an embed?

#

if so does anyone have any examples of an idea of how that would work following the

await channel.send(embed=embed)
thin raft
#

publishing an embed?

blissful badge
#

For some reason cannot get it to work

blissful badge
hushed galleon
#

!d discord.Message.publish

unkempt canyonBOT
#

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

Publishes this message to the channel’s followers.

The message must have been sent in a news channel. You must have [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages "discord.Permissions.send_messages") to do this.

If the message is not your own then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") is also needed.
thin raft
#

since when is that smt

hushed galleon
#

store the message object returned by send() and you can call publish() on it

young dagger
blissful badge
#

oh thats not too bad

hushed galleon
# young dagger Can you give me an example of this please?
@tasks.loop(hours=24 * 3)
async def my_loop():
    ...

@my_loop.before_loop
async def before_my_loop():
    await asyncio.sleep(<seconds_until_12am>)``` as for calculating the seconds, figure out the next due date then subtract the current time (datetime is probably the easiest to use for this)
blissful badge
hushed galleon
#

send() returns a Message object, by storing it i mean assigning the result to a variable so you can do things with that message object

#
message = await ctx.send("Hello...")
await message.edit(content="...world!")```
blissful badge
#

ohhhhhhhh ok, and in this case publish is an attribute of message so I should be able to just put it as

await message.publish()

right?

hushed galleon
#

yup

blissful badge
#

In response to that its throwing me this

code I have is

        channel = self.bot.get_channel(int(dest.content))
        message = await channel.message.send(embed=embed)
        await message.publish()
hushed galleon
#

yeah what the error says, channel.message doesnt exist

thin raft
#

message.channel.send

blissful badge
#

ahh

#

why would it have worked fine before though?

thin raft
#

or channel.send in your case

blissful badge
#

okok

#

asking so I know for next time, still learning a lot of this.

appreciate the help.

hushed galleon
#

if it was working earlier, i dont think that code was what your bot was running

blissful badge
#

it was working just like that minus the publish bit

#

no joke

#

with that code

young dagger
hushed galleon
# blissful badge with that code

i still have my doubts about that because its like if a person said "spiders have 2 legs" and then they showed a picture of a spider with two legs
the picture affirms their statement, but you know it objectively doesnt make any sense

#

what "message" could channel.message possibly refer to? there's thousands to choose from

#

that being said i dont know enough about how the bot reacted for me to make any clear judgement, but my assumption would be something more simple like accidentally changing the original channel.send() to channel.message.send(), then forgetting to save until the publish() line was added

blissful badge
#

that is entirely possible in fairness, but i dont believe i had edited that line in a while. who knows, regardless the solution provided did help, thank you 🙂

hushed galleon
blissful badge
#
ALLOWED_ROLES = (893639927928062032, 159107041896562688, 712725199161786429, 759773665575043073, 829569153136066572,)
bot.add_check(lambda ctx:
any([r in ctx.author._roles for r in ALLOWED_ROLES]))

is this not the right format for limiting what roles it uses? I thought it was working fine but seems to be acting up now and allowing anyone to use it

idle palm
#

Hello,

In a slash command i have an argument to input a discord.Role but it only allows the user to enter one role

How can i allow the user to input 5 optional roles (They must at least input 1 role and 5 is the max they can input)

fading marlin
#

you can have multiple arguments for the different roles, but besides that there's not much else you can do

meager chasm
#

Maybe u can use a view with 5 select menus :P

fading marlin
#

or just 1 and have a maximum selection of 5 🤷

blazing flint
blazing flint
shrewd thistle
#

Can any1 help me with the skycrypt api/hypixel api and how to retrieve info and convert it from a list to just the data dm me plz

smoky sinew
shrewd thistle
#

Yes it is

smoky sinew
#

just because it involves a discord bot doesn't mean you should post it here because not everyone works with the hypixel api

shrewd thistle
#

Cause I’m making a hypixel bot with custom commands

#

Fair enough okay

#

Sorry

unkempt canyonBOT
#

Hey @slate swan!

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

smoky sinew
#

have you tried seeing what user_answer is?

smoky sinew
#

yes but what actually is it

#

aren't you trying to use float on a list there anyways?

blissful badge
#

If I wanted to have a command cancelled based on a specific response from an if statement, is it "exit" that would be used? Or something else

#

Like if I used "next" but instead wanted it to just stop the command entirely

#

exit isn't working is why im asking

uneven hearth
#

i forgot how to do it - how do i change the direction of the selection options once clicked? because once i click it, it goes down.

blissful badge
smoky sinew
#

no that's what continue/break is for

blissful badge
#

ohhh

#

got them flipped then

appreciate you

#

thats not doing it

#

getting the code

#
        await ctx.send(embed=embed)
        await ctx.send(f"Tagging @{role_message}.")
        await ctx.send(f"Sending to #${dest}.")
        await ctx.send('**Last Chance**, does all this look correct? Yes or No.')
        confirmation_message = await self.bot.wait_for("message", check=lambda m: check(m) and any([
        "yes" in m.content.lower(),
        "no" in m.content.lower()
        ]))
        if "yes" in confirmation_message.content.lower():
            next
        if "no" in confirmation_message.content.lower():
            await ctx.send("The embed has been succesfully cancelled, please try again.")
            return       
#

it seems to be ignoring return?

smoky sinew
#

what does "next" mean

#

!d next

unkempt canyonBOT
#

next(iterator)``````py

next(iterator, default)```
Retrieve the next item from the [iterator](https://docs.python.org/3/glossary.html#term-iterator) by calling its [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method. If *default* is given, it is returned if the iterator is exhausted, otherwise [`StopIteration`](https://docs.python.org/3/library/exceptions.html#StopIteration "StopIteration") is raised.
smoky sinew
#

this is probably not what you wanted

blissful badge
#

I thought next is what I would use to move on in the command

smoky sinew
#

no you don't need that if statement at all

#

where did you get this information from

blissful badge
#

uhhh

#

nowhere just taking my own stab at writing my own if statement lol

#

clearly its going well

marble current
#

if i do
from FILE_NAME import FUNCTION can i just use that command from the main file? or do i have to run the other one or sum

slate swan
#

guys now i want create a file in a folder that the running file of python run in.

#

and ofc with os.listdir()

unkempt canyonBOT
#
The for-else block

In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.

Here's an example of its usage:

numbers = [1, 3, 5, 7, 9, 11]

for number in numbers:
    if number % 2 == 0:
        print(f"Found an even number: {number}")
        break
    print(f"{number} is odd.")
else:
    print("All numbers are odd. How odd.")

Try running this example but with an even number in the list, see how the output changes as you do so.

north kiln
#

hi I was trying to sync new slash command I made to a specific test guild but the commands I synced before made shows up twice in the test guild if I specify the guild when using tree.sync. Not sure what I have to do here

#

so I think I solved this issue now 😅

tight fog
#

hey I have a question

#

if I want to prevent people with Discord roles that are too low from using a certain bot command, how do I do that

blazing flint
#

how do I use this bot

#
await interaction.edit_original_response(content="Audio downloaded successfully.", file=discord.File('./audio.mp4'))```

is my code, and I am getting an error that edit_original_response does not have a "file" argument
#

bruhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
vale wing
# tight fog if I want to prevent people with Discord roles that are too low from using a cer...

Not clearly specified what you need, however here are 2 possible solutions

  1. If you want to restrict users with roles or your bot is multiserver with different configured roles, you need to use custom check (see @commands.check in docs)
  2. If your bot is single guild and you want users only with certain roles to be allowed to use command, use @commands.has_roles or @commands.has_any_role.
blazing flint
#

?

#

I was asking how to use the python bot

vale wing
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
blazing flint
#

!d discord.Attachment

blazing flint
#

I know there are multiple things that I am doing wrong here

#

but I don't know how to fix them

smoky sinew
#

could you not just look at the docs to see all the arguments

slate swan
#

i am creating a discord command to repeat what i say, the command is returning a error

the command

`import bot

@bot.command()
async def say(ctx, , arg):
await ctx.send(f"{arg}/n)"
"
* **/n"
f"{ctx.author.mention}/n")

if name == 'main':
bot.run_discord_bot()`

The error it is giving me

AttributeError: module 'bot' has no attribute 'command'

#

Can someone tell me how i could fix this issue?

#

im extremely new to coding, lol.

smoky sinew
#

what is import bot

#

and bot.run_discord_bot

vocal snow
#

I would really recommend learning some basic python first; it looks like you're just gluing together random code

slate swan
#

💀

#

because i kinda am, LOL

smoky sinew
#

you need to import discord.py first, then create a bot instance and register commands using it

vocal snow
#

!resources

unkempt canyonBOT
#
Resources

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

vocal snow
#

Bunch of free courses and books here

slate swan
#

ty

smoky sinew
# slate swan ty

e.g. ```py
from discord.ext import commands
import discord

intents = discord.Intents.default()
intents.message_content = True

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

@bot.command()
async def my_command(ctx):
...

slate swan
#

ty

#

can anyone help me out with this ?

slate swan
shrewd fjord
# slate swan

currently opencv or cv2 whatever u say doesnt work on replit

stable raptor
#

any tips on how to learn discord bot python?

meager chasm
slate swan
#

then it won't run @shrewd fjord ?

patent lark
meager chasm
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @patent lark until <t:1680586269:f> (10 minutes) (reason: newlines rule: sent 12 consecutive newlines in 10s).

The <@&831776746206265384> have been alerted for review.

cerulean geyser
#

!unmute 647261111841980418

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @patent lark.

cerulean geyser
#

For longer code snippets please use a paste site

#

otherwise our bot will mistake you for a spammer

patent lark
#

got it

shrewd fjord
upbeat otter
#

I think it did before

patent lark
patent lark
glad cradle
#

Have you saved the file?

patent lark
#

yes

#

i was able to fix my issue, user error. :/

slate swan
#

someone pls help me resolve this

#

:/

shrewd fjord
slate swan
slate swan
slate swan
slate swan
#

wht u want the bot to do?

slate swan
#

its an anime game

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

how am i supposed to save the user data?

vale wing
#

In a database

slate swan
vale wing
#

Yeah unless it's non-sql database like mongo

slate swan
vale wing
#

It's a valuable skill

#

And it's easy to learn

#

So definitely

slate swan
#

oki

jolly prism
#

can someone help me with it

lyric halo
#

is anyone here i need help

jolly prism
#

even i need help :/

naive briar
slate swan
#

command " python.execlnTerminal-icon" not found

#

i am having this error in vs code

slate swan
#

how do i do a fricken button 😦

#

i have been trying for 3 hours now

#


import discord
from discord.ext import commands, tasks
from discord.ext.commands import Bot, Context
from discord.ui import Button


intents = discord.Intents.all()
intents.bans = True
intents.dm_messages = True
intents.dm_reactions = True
intents.dm_typing = True
intents.emojis = True
intents.emojis_and_stickers = True
intents.guild_messages = True
intents.guild_reactions = True
intents.guild_scheduled_events = True
intents.guild_typing = True
intents.guilds = True
intents.integrations = True
intents.invites = True
intents.messages = True # `message_content` is required to get the content of the messages
intents.reactions = True
intents.typing = True
intents.voice_states = True
intents.webhooks = True
intents.members = True
intents.message_content = True
intents.presences = True


prefix = "."
bot = commands.Bot(command_prefix=prefix,intents=intents, description="Desc", help_command=None)

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name=f"{prefix}help"))
    print("Bot has successfully logged in as: {}".format(bot.user))
    print("Bot ID: {}\n".format(bot.user.id))


@bot.event
async def on_message(message: discord.Message) -> None:
    if message.content == ".button":
        view = discord.ui.View()
        button = discord.ui.Button(label="Click me!")
        view.add_item(button)
        await message.channel.send("Hello!", view=view)
        
        def check(m):
            return m.channel == message.channel

        try:
            interaction = await bot.wait_for("button_click", check=check, timeout=30)
            await interaction.response.send_message("You clicked the button!")
        except asyncio.TimeoutError:
            await message.channel.send("You didn't click the button in time!")
bot.run(token="token")
#

it spawns the button and will get the timeout error and send the msg but it wont get if i click the button

merry cliff
#

my guy

#

discord.Intents.all() should be fine, you don't need to manually enable all of them

#

for the button, you must create a callback function for it to do anything when pressed

#

I will demonstrate 1 in a class (for more complicated stuff) and one inside a command

#
class CustomButton(discord.ui.Button):
    def __init__(self):
        super().__init__(style=discord.ButtonStyle.red, label="LABEL")

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.edit_message("you pressed the button!")

class CustomView(discord.ui.View):
    def __init__(self):
         self.add_item(CustomButton(0, 0))

then in your command, just add view=CustomView() when you send it

#

I just yoinked some of my code from me making a game if ur wondering about the variables

#

and here is a button made INSIDE a command:

#

(this was inside a cog)

#

I heavily recommend NOT defining the buttons inside a command as you are unabke to use them in different commands and it is less efficient overall.

#

@slate swan

slate swan
merry cliff
#

if you are using my recommended method of using classes, you will need from discord.ui import Button, View

#

no wait you dont

#

it calls from the discord library

#

my bad @slate swan

brisk edge
#

Sorry for interrupting a convo, just wanted to know if slash commands are exclusive to the client side of discord.py, and if not how can I use them with cogs?

merry cliff
#

wdym by client side

#

a bot cannot interact with other bots if that's what ur wondering

brisk edge
#

Meant to say @client.event thingy (I'm sorry I don't know how this is called)

#

My bot uses @bot.event for reference

merry cliff
#

to make a slash command?

brisk edge
#

yep that

#

I just want them to pop like this on the chat

merry cliff
#

those are slash commands, or what discord.py calls app_commands

#

to make them in your main.py file (not a cog), do @bot.tree.command(args) , and in cogs, do @app_commands.command(args) where you usually put @commands.command()

slate swan
#

just like a simple "button pressed"

merry cliff
#

as an example

brisk edge
# merry cliff to make them in your main.py file (not a cog), do `@bot.tree.command(args)` , an...

So if I were to have this

class CommandHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='test')
    async def test_command(self, ctx):
        """Says hello"""
        await ctx.send('Hello!')```

It'd be this?

```python
class CommandHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name='test')
    async def test_command(self, ctx):
        """Says hello"""
        await ctx.send('Hello!')```
merry cliff
#

buttons are interactions, so they don't take context (ctx)

#

interaction: discord.Interaction

#

instead of ctx: discord.Context

slate swan
#
async def on_message(message: discord.Message) -> None:
    if message.content == ".button":
        button = CustomButton()
        await message.reply("this is a button", view=button)

how do i do this 😦

merry cliff
#

same thingwith slash commands

slate swan
#

im using the class

merry cliff
slate swan
#

im just testig

vale wing
#

Use commands framework

#

And for buttons check examples on repo

#

If you need links tell me

slate swan
#

i have tried for hours on end multiple libs

#

tried all there examples

merry cliff
vale wing
#

Best is disnake! (in my honest opinion)

merry cliff
#

cringe

slate swan
#

can you provide a link to the example of the discord button example ?

vale wing
merry cliff
#

MY BAD

vale wing
merry cliff
vale wing
#

I didn't even know OOP when I started

merry cliff
#

same

#

but its so helpful

vale wing
#

Bot development was a great entrypoint for me

slate swan
#

how is that not int

vale wing
slate swan
#

should i use str ?

vale wing
#

Iirc you can somehow increase the limit but I am not sure and can't tell you how exactly

#

str will work but that method might be better

#

What library do you use?

slate swan
slate swan
vale wing
#

!d disnake.ext.commands.Param

unkempt canyonBOT
#
disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, ...)```
A special function that creates an instance of [`ParamInfo`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.ParamInfo "disnake.ext.commands.ParamInfo") that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.

See [Parameters](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-syntax) for more info.
vale wing
#

There's large kwarg

slate swan
brisk edge
whole shoal
#

How.do you import
discord-py-slash-command

merry cliff
whole shoal
#

Hm

#

Docs on slash commands?

naive briar
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
whole shoal
#

Alr ty

whole shoal
#

Anyone know how can I add an optional param in slash commands

hushed galleon
unkempt mauve
#

how do I get bot uptime?

deft quartz
#

Start a time variable in on_ready and substract it from the time when the command for uptime is sent

unkempt mauve
hushed galleon
#

or if you want to be a bit more fancy, store a list of timespans of when your bot is online

hushed galleon
#

datetime + bot vars would be most convenient for implementing either option

blissful badge
#

having a bit of trouble with an if statement seeing if anyone can steer me in the right direction....

        await ctx.send(embed=embed)
        await ctx.send('Does this look correct? Yes or no.')
        confirmation_message = await self.bot.wait_for("message", check=lambda m: check(m) and any([
        "yes" in m.content.lower(),
        "no" in m.content.lower()
        ]))
        if "yes" in confirmation_message.content.lower():
            next
        if "no" in confirmation_message.content.lower():
            await ctx.send("The embed has been succesfully cancelled, please try again.")
            exit

it accepts both yes and no but if you say no it still says it cancelled the embed but it continues on with the rest of the command.

For context this is inside of a multi step embed command where the user sets the individual parts of the embed by responding to the bot. Everything works except for this loop part so I know its just my if statement thats messed up

#

it still sends the "the embed has been succesfully cancelled, please try again" but doesnt exit the command

hushed galleon
#

next and exit are just functions, both of which you likely dont want to call

#

generally an exception or return statement is how you'd terminate a function early

unkempt mauve
uneven hearth
#

is it possible to dm someone with components?

blissful badge
hushed galleon
unkempt mauve
#

oh thank you. I didnt read your message clearly

hushed galleon
blissful badge
#

Oh and it'll just move on in response to yes because of the check

#

that makes sense

blissful badge
# hushed galleon i guess sure, or you can remove the yes entirely - if its not no then you know i...

that fixed it 🙂

also, confused on what I am doing wrong in this code bit py await ctx.send(f"Sending to: <#${dest}>.")
that its outputting it as this

Sending to: <#$<Message id=1092811984937943172 channel=<TextChannel id=1065685023853920258 name='bot-testing-zone' position=7 nsfw=False news=False category_id=1065685023853920256> type=<MessageType.default: 0> author=<Member id=288522211164160010 name='ian' discriminator='5555' bot=False nick=None guild=<Guild id=1065685023283499118 name="Ian's Workshop" shard_id=0 chunked=True member_count=7>> flags=<MessageFlags value=0>>>.
#

I know I have gotten this to work before and from my research that is the right format for that, I just cant figure it out

#

"dest" being a channel ID

hushed galleon
#

well apparently dest is a message object

#

if you want to mention the channel of that message you'd use <#{message.channel.id}> (no $ sign), or the convenient property {message.channel.mention}

blissful badge
#

So that makes sense but how would I convert the "dest" object over to "message.channel.id"? just using an "=" statement above?

hushed galleon
#

dest is your message, so to access its channel you would write dest.channel

#

i mean if you want to alias it (set it to a variable) before writing your f-string sure

#

but you're free to write the entire expression within your f-string

blissful badge
#

ahhhh so I just append dest

#

I forget I can do that to objects sometimes

blissful badge
hushed galleon
#

then do you have the channel object for that announcement channel?

blissful badge
#

Unsure how to answer that tbh

        await ctx.send('What channel should I send this in? Please provide me with the channel ID.\n- #sc-news: 569635458183856149\n- #general-news: 803341100618219540\n- #sc-patch-notes: 585952222853201941')
        dest = await self.bot.wait_for('message', check=check)

this is how I'm getting announcement channel id

hushed galleon
#

oh thats you meant by "dest being a channel ID", the message content contains the actual ID

#

imo this is what you want to use a channel select menu for, but regardless you'll want to get the channel object using that ID

#

!d discord.Guild.get_channel

unkempt canyonBOT
#

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

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
blissful badge
hushed galleon
#

remember that dest is a Message object, not a string

hushed galleon
sick birch
blissful badge
blissful badge
slate swan
#

@blissful badgehi

blissful badge
hushed galleon
#

there are several different data types you'll need to work with to work towards sending that announcement: ```py
message = await bot.wait_for("message", ...)

^ Message object

message.content

^ a string, which presumably looks like '569635458183856149'

int(message.content)

^ an integer, which would look like 569635458183856149

channel = ctx.guild.get_channel(int(message.content))

| ^ the current guild

= the GuildChannel object that would be your #sc-news channel

(or possibly None)

await channel.send(f"This is an announcement to {channel.mention}")

#sc-news```

blissful badge
#

thats right "int"

#

mudkip has been reminding me of that so much

#

ok ty cracks lemme try to implement that

blissful badge
slate swan
#

can i ask which type of bot u r trying to make

blissful badge
indigo basalt
#

Is it possible to edit a embed with a button click
e.g. after a button click your name shows up in the embed?

slate swan
#

bruh

blissful badge
blissful badge
mighty sun
#

Hello, when I want to put my bot online I have this problem that appears ... possible to help me solve it? thank you in advance

blissful badge
#

@hushed galleon I actually got it to do exactly what I wanted with just this line

        await ctx.send(f"Sending to: <#{dest.content}>.")
#

ignore additional screenshot

#

which is weird because it knows what "dest" is, but then when I try to do

await ctx.send(f"Tagging: <@&{role_message}>.")

it doesn't know what "role_message" is

"role_message" just being another identifier like "dest"

naive briar
#

If the message content is a channel ID, then it will

blissful badge
#

just from what cracks said it seemed like it needed more

so just clarifying

slate swan
slate swan
mighty sun
#

yes, but on my site I can't add a folder, so I took out the relay of the folder, that's why? but then I have to mark what in the .main file?@slate swan

slate swan
#

like for strt commands diffrent

mighty sun
blissful badge
#

I would recommend doing so using cogs and extensions yeah

slate swan
mighty sun
slate swan
mighty sun
#

ok

blissful badge
# slate swan bruh cogs and extenions?

Its a lot easier then it seems.

Here is an example cog file

import discord
from discord.ext import commands

class Responses(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if self.bot.user.mentioned_in(message):
            print("SCNewsBot has been mentioned.")
            await message.channel.send("test")

    @commands.command(name='commands')
    async def send_data(self, ctx):
        await ctx.send("test")
        channel = self.bot.get_channel(1086293466054656100)
        author = ctx.author.name
        await channel.send(f"Command list access by {author}")

    @commands.command()
    async def ping(self, ctx):
        await ctx.send("Hello! I am here.")


async def setup(bot):
    await bot.add_cog(Responses(bot))
mighty sun
#

from os import environ as env

from dotenv import load_dotenv
from relay_bot import RelayBot

load_dotenv()

def main():
relay_bot = RelayBot(
env.get('SOURCE_CHANNEL_ID'),
(
env.get('PRIORITY_DESTINATION_CHANNEL_ID'),
env.get('FALLBACK_DESTINATION_CHANNEL_ID')
),
env.get('ROLE_ID')
)
relay_bot.run(env.get('BOT_TOKEN'))

if name == 'main':
main()

blissful badge
#

and then here is what you need in your main file to import a cog

extensions = ("embed","responses","formats")
slate swan
#

is there any docs for cogs??

blissful badge
#

yes let me grab it

slate swan
#

bruhhhhh

mighty sun
#

@slate swan 'from os import environ as env

from dotenv import load_dotenv
from relay_bot import RelayBot

load_dotenv()

def main():
relay_bot = RelayBot(
env.get('SOURCE_CHANNEL_ID'),
(
env.get('PRIORITY_DESTINATION_CHANNEL_ID'),
env.get('FALLBACK_DESTINATION_CHANNEL_ID')
),
env.get('ROLE_ID')
)
relay_bot.run(env.get('BOT_TOKEN'))

if name == 'main':
main()'

slate swan
#

ty

mighty sun
#

since I took my relay file out of the folder I have to write at the top of the hand ? just import relay ?@slate swan

smoky sinew
#

remember they're not the same

blissful badge
smoky sinew
#

extensions can be loaded without any cogs, and cogs can be added without being in an extension

blissful badge
#

this is all thats in my main file for my extensions

#

ohhhh

#

ur correcting my terminology

#

thank you

blissful badge
blissful badge
unkempt canyonBOT
#

Hey @blissful badge!

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

blissful badge
#

Oops

slate swan
#

what when this if is False if "yes" in tag_confirmation.content.lower():? then the varriable role_message wont be defined

#

and you encounter this error

smoky sinew
#

why are you using the next thing again

blissful badge
#

forgot to remove that from our previous convo, fixing

#

oh yeah cause it does this

slate swan
#

cause you need to do something when this if is True

blissful badge
#

I do

slate swan
#

you cant just define if something and do nothing

blissful badge
#

oh

#

outside of defining I have to do something

#

but theres nothing else i need it to do lol

slate swan
#

so why do you check for that

#

if you dont need it

blissful badge
#

What?

slate swan
#

if you dont need this if remove it

blissful badge
#

I do need the if statement, it has to define role_message

smoky sinew
blissful badge
#

but I thought return stops it?

smoky sinew
#

delete the whole if "yes" part

smoky sinew
blissful badge
#

this isn't for the preview

smoky sinew
#

then remove the if statement entirely for if "no"

blissful badge
#
        await ctx.send('Do I need to tag someone? Yes for single post or final in a set, no for first if you need a second embed.')
        #role_message = await self.bot.wait_for('message', check=check)
        tag_confirmation = await self.bot.wait_for("message", check=lambda m: check(m) and any([
        "yes" in m.content.lower(),
        "no" in m.content.lower()
        ]))
        if "yes" in tag_confirmation.content.lower():
            await ctx.send('What role should I tag? Please provide me with the role ID.\n- scnews: 620025828079697920\n- gennews: 803343410794594385\n- patchnotes: 620025894559547412')
            role_message = await self.bot.wait_for('message', check=check)
            whototag = role_message

            await ctx.send('What is the tag preview?')
            tag_preview = await self.bot.wait_for('message', check=check)
        if "no" in tag_confirmation.content.lower():
#

ah ok

#

thats kinda where i was getting cause cracks and I talked about something similer earlier

#

ok so here is where that issue is presenting itself again which @slate swan you pointed out earlier

for this section that pulls said "role_message" if I say no to needing to tag anyone it fails cause role_message has no content to it

        await ctx.send(f"Tagging: <@&{role_message.content}>.")
#

so trying to figure out how to get it to not error out the whole command if I say no to the earlier question that defines role_message

smoky sinew
#

just send the tag in the if statement

#

you should really use a converter instead of manually tagging the id

blissful badge
#

So I can't send it in the if statement

blissful badge
#

sorry just proud of myself, i fixed it myself with an if statement on the first try!!!!

slate swan
blissful badge
#
@bot.event
async def on_message(message):
    if message.channel.type == discord.ChannelType.news:
        await message.publish()
        return

having some issues making this instead work with specific channels vs ALL news channels.

I've tried the usual things like calling out the channel and publishing any messages in the channels but its not doing it.

any ideas?

slate swan
#

hello, i am doing a custom timezone command and i need help converting an UTC offset to a timezone name with whatever lib, i tried searching online for some results but none worked for me

thin raft
# slate swan hello, i am doing a custom timezone command and i need help converting an UTC of...
left dew
#

astimezone(datetime.timezone.utc)

error:
AttributeError: type object 'datetime.datetime' has no attribute 'timezone'

slate swan
#

!d datetime.timezone

unkempt canyonBOT
#

class datetime.timezone(offset, name=None)```
The *offset* argument must be specified as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "datetime.timedelta") object representing the difference between the local time and UTC. It must be strictly between `-timedelta(hours=24)` and `timedelta(hours=24)`, otherwise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.

The *name* argument is optional. If specified it must be a string that will be used as the value returned by the [`datetime.tzname()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzname "datetime.datetime.tzname") method.

New in version 3.2.

Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes.
slate swan
#

not datetime.datetime.timezone

left dew
smoky sinew
left dew
#

yea

smoky sinew
#

that's the problem

left dew
#

do i just need import datetime?

smoky sinew
#

yes, and switch the rest of your code to use datetime.datetime instead

left dew
#

ok

#

ty

left dew
smoky sinew
#

!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.11)") for presentation within Discord.

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

<t:1680630195:f>

left dew
#

yea

smoky sinew
#

or just use a nicer format in strptime

potent spear
#

you can use the util mentioned above

left dew
potent spear
left dew
#

<t:{}:F>

#

but what do i put in the {}

potent spear
#

that would be doing it manually, that's why you want to use a util...

#

that does it FOR YOU

#

by giving it a datetime object, it "converts" it into discord's sexy format

left dew
#

ohh

#
confirm_time = datetime.strptime(res["confirmed"], "%Y-%m-%dT%H:%M:%SZ")
            nicely_formatted_date = discord.utils.format_dt(confirm_time)```
#

like that?

potent spear
#

<t:1680630573:f>
<t:1680630573:F>
<t:1680630573:R>

left dew
#

dayum

#

how do i edit style? style= ...

potent spear
#

check the docs what options you can pick from

potent spear
left dew
#

style = <t:{confirm_time}:F> ?

potent spear
#

no man

#

..... = .....format_dt(<your_datetime_obj>, style="F")
for example

left dew
#

oh

#

i see

slate swan
#

anyways why is the the hex code 0xfff shown as blue in an embed?

left dew
#

that worked tysm

potent spear
#

gl!

potent spear
slate swan
#

i asked why 0xfff is shown as blue because originally its white

#

i didnt even use ansi

waxen summit
#

Guys I want to mirror a telegram channel into discord. How would I do it without being an admin ?

still obsidian
#

How do I add parameters/arguments to an application command?