#discord-bots

1 messages Β· Page 377 of 1

slate swan
#

yes only not token

#

idk

dense falcon
#

Also, what people have said is mostly right, making a discord bot is definitely not a beginner challenge and it would be much simpler to start with something smaller, like calculators. They seem simple and boring but by getting to know how it works you gain the experience you need for bigger projects

dense falcon
#

tbh personally I was lucky to be able to revise python in high school since they only offered it as a club

#

ah nice

#

I almost ended up purely a GDScript and HTML kid not gonna lie

#

sobs loudly

#

I have almost a whole discord bot made complete with moderation and profiles and I definitely should not be at this stage

#

I spent a day trying to figure out why the database wasnt returning in my script, it was because I called the table settings and referenced it as servers

#

I broke mine up into cogs so i think mine's like 600 or so too?

#

I made it for a community and therefore I made a command that takes a save file and outputs it with max currency

#

we kinda wanted a bot like, a year ago, did barely anything with it, and now a year later I picked it up and got wayyy too far in like, a couple weeks

slate swan
#

i want it to send 1 message into the ticket

#

it send 2 msg

dense falcon
# slate swan

I think it sent again because of the Pin message but i could be wrong

#

looking at your code it's gonna send every time someone says ANYTHING

dense falcon
#

yes but it still holds

slate swan
#

only if bot sends

slate swan
#

per channel

dense falcon
#

ngl i dont know

slate swan
#

how to make like

#

it sends to every new channel a msg

#

so for example i create a random channel then it will send msg in there..

slate swan
slate swan
#

yes but that not all

#

can I send you code in dms

#

no actually send me your code (few lines) I'll add and send

slate swan
slate swan
#

import discord

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('hello'):
    await message.channel.send('Hello!')

@client.event
async def on_message(message):
if str(message.author.id) == "790338464385073203":
await message.channel.send('Hello, please explain what ')

client.run('TOKEN HERE')

#

so basically u want I to

#

send msg in every channel

#

ik can u fix

slate swan
scarlet tiger
#

Oh ok

slate swan
#

ik

#

but im trying to add a addon

#

kinda extra option

#

uhm

#

idk

scarlet tiger
#

He's new, explaining it that way doesn't help.

slate swan
#

i do

#

i explained....

#

πŸ₯Ά

#

i want this could not make a good pic but should work

#

ja

#

ja will gwn iets voor ticket en probeer beetje te leren πŸ€·β€β™‚οΈ

#

ik

#

heb all ticket bot

slate swan
#

Why?

#

yes

#

that no problem

scarlet tiger
past spire
#

how do i use modules in @bot.command()? like, i want async def variable(ctx) to be on another file, is that even possible?

slate swan
past spire
#

cogs? what's that

#

i am trying to do that, but there are few problems

dense falcon
#

They have to be set up in a class defined as a cog too

#

and then you load the file as an extension

past spire
#

can i add more than one functions in cog file?

dense falcon
#

yes

past spire
#

enlighten me please

scarlet tiger
past spire
#
@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')```
let's say i want to make this line to work with another file `response`
slate swan
dense falcon
#

as long as all commands are in the class in the cog file and are @commands.command instead of @bot.command, and use self as a parameter

past spire
#

yesss

dense falcon
#

theres more I can't remember

scarlet tiger
slate swan
past spire
#

i can do database

#

you mean, make a dictionary?

scarlet tiger
slate swan
#

i show code

quick gust
#

json files arent databases

#

No, they should never be

scarlet tiger
# slate swan

Hmmmm, you could use an embed message and have it have a button that opens the ticket

past spire
#

i can do .db files with sqlite3, it worked, but i can't go further as i haven't fully read the API, and i still need to know how to fetch userid, channelid and stuff

slate swan
#

i want something simple

slate swan
dense falcon
scarlet tiger
past spire
#

ohh

unkempt canyonBOT
#

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

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

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
past spire
dense falcon
#

yeah the API is really helpful

dense falcon
scarlet tiger
past spire
past spire
dense falcon
#

nvm if you use a different library than sqlite3 I probably can't help lmao

#

unless there isn't much difference

scarlet tiger
dense falcon
#

oh nice

past spire
past spire
#

ohh

#

so, what's the difference between @bot.command() and @client.event()??

open cobalt
#

hey guys connected to the gateway and becoming events from the websocket, rly nice

dense falcon
#

a command is ran by the user and an event is something that just happens like message sending or deleting

past spire
#

which one should i use??

open cobalt
#

how should I make the event handler or how should I handle any events that I receive through the websocket?

past spire
#
bot = commands.Bot(command_prefix='!', intents=intents)```
#

i did this btw

open cobalt
#

any ideas?

past spire
open cobalt
#

ok

past spire
#

so, if i do !somethin, bot have to go in @bot.command() and search for async def somethin(ctx), right?

open cobalt
#

anyone in here using websockets for your bots?

dense falcon
#

self isn't needed if it isn't commands.command right?

past spire
#

and, i have to do @bot.command() again and again to to define new async class

#

let me change my code from ctx to self

#

ohh, you mean i do ctx for main file and self if i link to other?

#

ok, got it

scarlet tiger
past spire
#

so, it is just working as if else statement, right?
how do i make it work like a switch statement so it does not have to look for ever @bot.commands()

golden portal
open cobalt
golden portal
open cobalt
past spire
#

let me give you an example, i want to use cogs
lets say user send a message and i save the message without prefix in a variable, let's say x for now
and then the @bot.command works, and it sends the x value to other file where it perform cirtain things and send back the data

#

wait wait

golden portal
past spire
#

message is coming with prefix, !anything and user can do anything here, and i store message anything in x and run it in @bot.command

#

and then it sends x to other file

#

yes

open cobalt
golden portal
#

damn you're really writing this in raw websocket payload handling

past spire
#

can you give me example?

slate swan
golden portal
#

i recommend just using discord.py, it has command handling exactly what you're looking for

open cobalt
scarlet tiger
open cobalt
past spire
#

im so confused with this now

#

a lot of questions

scarlet tiger
golden portal
#

yea the lore goes pretty deep if you were to do it raw

scarlet tiger
open cobalt
#
    if message_obj["d"]["content"] == ">create_channel":
        channel = {"name": "Channel Test"} # More information if needed 
        requests.post(url=f"{API_BASE_URL}/guilds/{GUILD_ID}/channels", headers=header, json=channel)
        print("CHANNEL CREATED")
#

I need to type hint the content to str

golden portal
#

well by default command arguments are set to str

open cobalt
#

yes but for my editor the type of message_obj["d"]["content"] is string but to get the methods

past spire
# scarlet tiger Can you explain to me what you want to do?

yes
so, i want my main file to be short, user send message as !message where message can be anything, and i used bot = commands.Bot(command_prefix='!', intents=intents) and @bot.command() async def hello(ctx): await ctx.send('Hello!') basically, so, here i want my class to work automatically and send the message to another response.py file where it does if else thing basically, and returns values to main file
main file will send the message to discord
something like this if you can understand

open cobalt
#

{'t': 'MESSAGE_CREATE', ............ socket is now running

past spire
#

i want to replace @bot.command() async def hello(ctx): await ctx.send('Hello!') with something useful

open cobalt
#

receiving events from websocket and change core with rest api

#
  if events["t"] == "READY":
      print("Bot has started.....")
scarlet tiger
past spire
#

save as in variable only
and yes

scarlet tiger
#

Allows managing multiple servers and users

past spire
#

for now, help me just sending hello from other file

open cobalt
scarlet tiger
#

It's basic Python

past spire
#

let me try 😭

scarlet tiger
past spire
#

bot = commands.Bot(command_prefix='!', intents=intents)
should i change this line?

open cobalt
scarlet tiger
past spire
#

it just sits around without any function

scarlet tiger
scarlet tiger
open cobalt
#

to learn

scarlet tiger
#

Yes, it is a good way to learn, but you will have many questions and problems

past spire
#

i did print(f'{bot}') lol

open cobalt
scarlet tiger
#

Why are you printing the bot object

golden portal
#

that is indeed the repr of a Bot object

open cobalt
#

repr

past spire
#

just trying to understand why i used it
all i know is that it is used for @bot.command

open cobalt
#

is a thunder method and used to present it as a string

scarlet tiger
open cobalt
#

Boo do you know what @ is in python?

past spire
past spire
open cobalt
#

is it essential to know what it means

scarlet tiger
open cobalt
#

if you dont know what that is you dont understand your code

#

but as a developer you need to understand every line you write and what it makes

past spire
#

that's why im here :)

open cobalt
#

Python was my first programming language but I did a calculator or a todo app or a guessing game

scarlet tiger
open cobalt
timber dragon
#

judging someone's python skills in the python server..

help them or not lol

past spire
#

i know basics, how to make classes, private variables etc

open cobalt
#

I am not judging anyone I am judging myself that I need to improve

scarlet tiger
open cobalt
#

dont judge me for using websocket

timber dragon
#

you don't have to use a library/wrapper if you can do it yourself like handling ratelimits etc

quick gust
open cobalt
#

I use json, requests, websockets , threading

#

time as well

finite salmon
#

Most discord api wrappers handle rate limits themselves

scarlet tiger
upbeat otter
timber dragon
finite salmon
#

Well yeah ig

open cobalt
#

guys dont judge me like this

#

I think you guys judge me and hate on me

upbeat otter
finite salmon
#

If you wanna do it from scratch it's just reinventing the wheel

open cobalt
#

Can I improve my python skills or not with the discord api

quick gust
#

you will improve your python skills with anything you code as long as you're learning new concepts and gaining experience

open cobalt
#

It is just a regular api with requests but indeed you need websocket and this I learned with threading

#

I learned about websockets and the threading module

#

yall hating on me for no reason despite i want to learn and improve

#

instead of reviewing my code I wrote

upbeat otter
#

you ain't getting nowhere using the requests module
You'll need to use the async version of anything that's possible

open cobalt
#

Guys, I give up and use the library it is better

upbeat otter
quick gust
open cobalt
#

you guys hate on me and dont want me to improve

upbeat otter
open cobalt
#

I am crying rn

slate swan
#

To be honest, making it from scratch just helps you understand how it all works under the hood

open cobalt
#

I go crying in a dark room and be there myself

upbeat otter
#

Ok.

quick gust
#

Ok πŸ‘

upbeat otter
open cobalt
upbeat otter
open cobalt
#

and the best part to learn. You said before asyncio so tell me

#

Asyncio is for asynchronous programming so the code is not line by line

slate swan
#

most of the stuff if not everything is documented on the discord developer portal, making it is just a matter of time

upbeat otter
# slate swan How so?

Just imagine the time you'll have to put into it and that will only result in messy code and endless bugs if you try to do it alone

scarlet tiger
slate swan
#

if you have the time, go for it

slate swan
#

nobody says you have to do it alone though

upbeat otter
open cobalt
#

Instead of explaining async and how that it is better Ash is just writing but I am here to learn

open cobalt
#

I thought so ray is the only one that understands it

slate swan
#

If you get going and keep making the wrapper, there are no downsides of that option in my opinion

open cobalt
#

ray, can you explain when asyncio should be in my code and why

#

can I send you some code and you can explain me?

slate swan
#

sure I can try

open cobalt
#

where is asyncio included @slate swan

slate swan
#

you could use aiohttp instead of requests to gain the async effect

async with aiohttp.ClientSession() as session:
  await session.post(url, headers=headers, json=json)
open cobalt
#

ok aiohttp

slate swan
#

and if it is possible you can also add some async stuff to the receive_data method, I assume it is related to responses so you could do something there

quick gust
#

Also, while loops are blocking

open cobalt
#

why is the async better, is it better if an error occurs and the code goes on and dont stuck that the bot doesnt crash?

#

I dont know what blocking ios

quick gust
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
open cobalt
#

@slate swan

finite salmon
open cobalt
#

ok now we getting somewhere, I need to lookup asyncio, aiohttp and blocking

limber jolt
#

Im asking iN here and not a help channel as It will prob be deleted when I come back from school but I installed Jishaku and when I tested It out in my server by doing !jsk py 1+1 It didnt do anything i have no idea what the error Is I made sure I loaded it correctly please help.

north kiln
#

show your code

#

where you loaded the modules and stuff

limber jolt
limber jolt
# north kiln where you loaded the modules and stuff
@bot.event
async def on_ready():
    print(f'{bot.user} is now running!')
    await bot.tree.sync()
    print("Loading Jishaku...")
    await bot.load_extension('jishaku')
    print("Jishaku loaded.")

    await bot.change_presence(status=discord.Status.online,
                              activity=discord.Activity(
                                  type=discord.ActivityType.playing,
                                  name="PixelPulse"))```
#

Thats my on_ready

north kiln
#

does any other jsk command work?

#

like jsk reload

limber jolt
north kiln
#

I think there could be a few possible reasons

  • the invoker is not the owner
  • the bot doesn't have message content intent
limber jolt
north kiln
#

message content intent is not whether it can send messages

#

where did you put your intents?

limber jolt
north kiln
#

there is probably some way to check if a module is loaded, let me check

limber jolt
north kiln
#

you can print(bot.cogs) to see if jsk is loaded ig

#

if not that it could be something with bot ownership

limber jolt
#

The bot and server

north kiln
#

then better wait for someone else to answer

limber jolt
north kiln
#

you might post the full code for more context

#

as I don't have any problem with it

north kiln
#

you just leaked ur token

#

reset it

#

it might be because you have overridden on_message

limber jolt
limber jolt
#

Done

north kiln
#

does ur bot respond to the colour command?

#

or any message command

limber jolt
#

So how do I fix It?

limber jolt
#

Its a import with no bot.events

north kiln
#

just do it

limber jolt
#

It aint telling me how to fix..

north kiln
#

do what the link says

#

jsk is just the same as your normal cog

#

await bot.process_commands(message) at the end of your on_message

limber jolt
north kiln
#

just add the line

#

if you aren't diving deeper

limber jolt
north kiln
#

no

#

just on on_message

limber jolt
#

Highlight what ones

fierce ridge
#

I want to add reaction role can some1 gimme example code or smthing (I'm new so can u make it simple?)

#

Ping or dm plz

north kiln
#

πŸ™ƒ

limber jolt
north kiln
#

probably

fierce ridge
#

Ping or dm πŸ™‚

limber jolt
north kiln
#

outside the if

limber jolt
north kiln
#

...

#

do you know indentations?

#

!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

limber jolt
#

It worked!!1

#

Thank you!!

dense falcon
#

my mind is slipping, what makes async super useful

turbid condor
#

Guys how to edit an embed such that the local image file should be inside the embed instead of outside. I have tried using the attachements kwarg in message.edit but that always sends the image outside of the embed

void zenith
copper flume
turbid condor
copper flume
#

without restarting

turbid condor
copper flume
#
Traceback (most recent call last):
  File "/path/to/venv/lib/python3.11/site-packages/jishaku/features/python.py", line 190, in jsk_python
    async for send, result in AsyncSender(executor):  # type: ignore
  File "/path/to/venv/lib/python3.11/site-packages/jishaku/functools.py", line 124, in _internal
    value = await base.asend(self.send_value)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/path/to/venv/lib/python3.11/site-packages/jishaku/repl/compilation.py", line 210, in traverse
    async for send, result in AsyncSender(func_g(*self.args)):  # type: ignore
  File "/path/to/venv/lib/python3.11/site-packages/jishaku/functools.py", line 124, in _internal
    value = await base.asend(self.send_value)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<repl>", line 3, in _repl_coroutine
    importlib.reload(ticket)
  File "/usr/lib/python3.11/importlib/__init__.py", line 148, in reload
    raise ImportError(msg.format(name), name=name)
ImportError: module cogs.ticket not in sys.modules```
I get this
turbid condor
turbid condor
#

I see you can load sys modules using the above link not local

turbid condor
copper flume
#

idk why i still get those errors

haughty summit
#

Hello guys

turbid condor
haughty summit
#

One question, I have implemented a cache based on dictionary filling after each command by user is received, would like running a background task to be cleaning the old entries (timestamp conditioon) after a certain time

copper flume
haughty summit
#

I have tried create_task with asyncio and I have a print inside

copper flume
#

whose attribute is reload_extension?

#

discord.reload_extension?

turbid condor
copper flume
#

ok let me do

haughty summit
#

but I just see the print in the beginning as I got the suggestion of initialzing the taskk inside on_ready function thet triggers once in the beginning

turbid condor
#

I haven't used jsk so don't know how that works

haughty summit
#

discord

#

version = '2.3.2'

turbid condor
haughty summit
turbid condor
#

ok so your task only runs once?

haughty summit
#

I want the task to run in the background

#

in a loop

#

maybe I am messing with on_ready

#

butI though I just create task and already have the freq running

turbid condor
haughty summit
#

yeah sure

#
async def clean_cache(interval, cache, max_age):
    log_Helius_Ifz("Checking cache to be cleaned . . .")
    while True:
        current_time = time.time()
        to_remove = []
        
        for key, value in cache.items():
            if current_time - value['timestamp'] > max_age:
                to_remove.append(key)
        
        for key in to_remove:
            del cache[key]

        await asyncio.sleep(interval) ```
#

this the function

#
async def on_ready():
    log(f"Logged in as : {client.user.name}")
    asyncio.create_task( clean_cache(30, wallet_cache, 60))
    asyncio.create_task( clean_cache(60, wallet_transactions_count_cache, 60)) ```
turbid condor
haughty summit
#

this the call

#

on-ready why I think is only initialization, so as first parameter is the sleep freq I guess would work triggering after that time is expired

#

but it does not

turbid condor
#

That's fairly easier

haughty summit
#

Hmmm

#

easiest approach I want yeah

#

not really used to discord lib

#

how could be that one used/implemented?

turbid condor
#
from discord.ext import tasks

@task.loop(seconds=5)
async def my_loop():
    print(1)


# to start the loop use
my_loop.start()
haughty summit
#

lemme try

#

thhank you man

turbid condor
#

And I'll suggest using setup_hook instead of on_ready in discord.py

#

For suck stuff or use a command to run such task

#

Idk who told you on_ready triggers only once but that's a big lie

haughty summit
#

nobody just silly enough myself to imagine that

#

I have print message with logging time

turbid condor
#

Well then your imagination was wrong

haughty summit
#

only execurting once as I dont see that command more than once I run the bot for the first time

#

could I open you dm?

turbid condor
#

Well I'd rather stay here since someone more experienced pops up

haughty summit
#

Hmmm

#

that's fine

turbid condor
haughty summit
#

this message only shows when I run the bot

#

not after so that's why it only executes once

turbid condor
#

Ah that this can happen frequently incase of reconnects which can occur during long runs

copper flume
#
0|bot  | future: <Task finished name='discord-ui-view-dispatch-31983369248b71f4ab4df97b531' coro=<View._scheduled_task() done, defined at /path/to/venv/lib/python3.11/site-packages/discord/ui/view.py:416> exception=AttributeError("'...' object has no attribute 'id'")>
0|bot  | Traceback (most recent call last):
0|bot  |   File "/path/to/venv/lib/python3.11/site-packages/discord/ui/view.py", line 429, in _scheduled_task
0|bot  |     return await self.on_error(interaction, e, item)
0|bot  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot  |   File "/root/cogs/ticket.py", line 95, in on_error
0|bot  |     raise error
0|bot  |   File "/path/to/venv/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
0|bot  |     await item.callback(interaction)
0|bot  |   File "/root/cogs/ticket.py", line 100, in close_ticket
0|bot  |     # if interaction.channel.permissions_for(interaction.guild.me).manage_channels is False:
0|bot  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot  |   File "/path/to/venv/lib/python3.11/site-packages/discord/abc.py", line 587, in overwrites_for
0|bot  |     if overwrite.id == obj.id:
0|bot  |                        ^^^^^^
0|bot  | AttributeError: '...' object has no attribute 'id'```
πŸ’€
turbid condor
#

Well your attribute which is '...' idk if you changed to this, is either none or does not have any attribute id

#

That's what above error says

copper flume
#

the line is commented πŸ’€

#

i changed the bot's class name

quick gust
#

can you show your code?

copper flume
#
class View(discord.ui.View):
    def __init__(self, bot):
        self.bot = bot
        super().__init__(timeout=None)

    async def on_error(self, interaction: discord.Interaction, error: Exception, item: Item[Any]):
        raise error

    @discord.ui.button(label="Close")
    async def close_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer()
        # if interaction.channel.permissions_for(interaction.guild.me).manage_channels is False:
        #     return await interaction.followup.send("...")```
shrewd apex
#

why do u have a class named ...

#

... is a thing in python called ellipsis

copper flume
#

i changed it

haughty summit
#

it does not seem to work

turbid condor
shrewd apex
#

what exactly dosent work

haughty summit
#
    if not clean_cache_transactions.is_running():
        clean_cache_transactions.start(wallet_cache, 20)
    if not clean_cache.is_running():
        clean_cache.start(wallet_cache, 20) ```
#
async def clean_cache(cache, max_age):
    log_Helius_Ifz("Checking cache to be cleaned . . .")
    while True:
        current_time = time.time()
        to_remove = []
        
        for key, value in cache.items():
            if current_time - value['timestamp'] > max_age:
                to_remove.append(key)
        
        for key in to_remove:
            del cache[key]

@tasks.loop(seconds=10)
async def clean_cache_transactions(cache, max_age):
    log_Helius_Ifz("Checking cache Txs to be cleaned . . .")
    while True:
        current_time = time.time()
        to_remove = []
        
        for key, value in cache.items():
            if current_time - value['timestamp'] > max_age:
                to_remove.append(key)
        
        for key in to_remove:
            del cache[key] ```
#

so different caches and implemented two identical tasks but just for testing

#

only getting this message

turbid condor
#

And both are not repeating or even starting?

haughty summit
#

just one starting

#

but not repeatingsecond one is not even triggering

turbid condor
haughty summit
#

yeah it is

#

even first approach should work

#

it shouldnt be that difficult to implementing back task for cleaning

turbid condor
haughty summit
#

I dont

#

just start in on_ready

#

getting this too but I have honestly ignored unitl now

turbid condor
#

Yeah it's due to you not quitting the while loop

haughty summit
#

oh wait

turbid condor
#

U need to break out of the while loop in your function

haughty summit
#

my bad

turbid condor
#

To consider it complete

haughty summit
#

didnt remove that from first approach

turbid condor
haughty summit
#

now both triggering!

#

lfg

#

Thank you @turbid condor

turbid condor
#

Yeah since the while loop made it stuck in a single continuation that's why the task wasn't restarting

haughty summit
#

yeah makes absolutely

#

was doing too fastdidint even realize

#

I would like to check few aspects about bot but too long I guess to type here

#

mostly related with not using builtin commands but scrapping them from message from user

#

also the warning I pasted previously

red sparrow
#

im trynna make my bot have a member pfp as an icon url but i dont really know how, tried this but doesnt work

turbid condor
turbid condor
#

What's ctx.server?

red sparrow
#

i tried getting the author server

turbid condor
#

its ctx.guild

#

And what you did is all wrong

#

You can get the user who ran the command using ctx.author

#

Then for the pfp you can do
ctx.author.avatar.url

red sparrow
turbid condor
#

Then use ctx.guild.get_member(int(id))

#

Or you use bot.get_member(id)

red sparrow
#

and after i do .avatar.url?

turbid condor
#

Just use that url where you want in embed

turbid condor
#

Since servers are called guilds in documentation

copper flume
#

how do i reload the cogs.ticket file?

#

I don't wanna reload the init.py

#

it is empty

turbid condor
#

Yeah should work tho you can just type Getpfp= bot.get_member(int(MaksimTarasov001))

copper flume
#

everything attribute starting with get_ takes id

copper flume
#

bot doesn't have any get_member

#

guild has, bot has get_user not get_member

turbid condor
#

Ah mb

#

Just checked it

red sparrow
copper flume
#

show code

turbid condor
#

Your member is returning nothing

red sparrow
copper flume
#

brother send the code, not screenshot

red sparrow
#
async def MaksimTarasov(ctx):
    Getpfp = bot.get_user(int(MaksimTarasov001))
    pfp = Getpfp.avatar.url
    embedVar = discord.Embed(title=Maksim_Tarasov["Name"], description="Team - Compton Chaos", color=Maksim_Tarasov["TeamColor"])
    embedVar.add_field(name="Position", value=Maksim_Tarasov["Position"], inline=False)
    embedVar.add_field(name="Archetype", value=Maksim_Tarasov["Archetype"], inline=False)
    embedVar.add_field(name="Height", value=Maksim_Tarasov["Height"], inline=False)
    embedVar.add_field(name="Weight", value=Maksim_Tarasov["Weight"], inline=False)
    embedVar.set_thumbnail(url=Maksim_Tarasov["TeamLogo"])
    embedVar.set_footer(text=Maksim_Tarasov["Userid"], icon_url=pfp)
    await ctx.send(embed=embedVar)```
red sparrow
turbid condor
#

Prolly your id is invalid or the user is not in guild, or the member isn't in cache

copper flume
#

then Getpfp is None

#

it means no such user associated with that id (in cache)

red sparrow
#

im on the server?

#

1193285339398295594

#

my user id

copper flume
#

directly put the id

red sparrow
quick gust
#

As an integer...

turbid condor
#

Try using await bot.fetch_user(int(id))

copper flume
#

print(Getpfp)

turbid condor
quick gust
#

Ah ok

red sparrow
turbid condor
#

await bot.fetch_user

copper flume
#

gotta learn some python

turbid condor
#

!d discord.User.avatar

unkempt canyonBOT
#

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

If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
red sparrow
#

Ty guys

turbid condor
#

Wild

copper flume
red sparrow
copper flume
#

as it fetches from API and does useless requests causing ratelimits

turbid condor
copper flume
vernal moth
#

File "C:\Program Files\Python312\Lib\site-packages\aiohttp\connector.py", line 1027, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

#

any1 could help to fix this

copper flume
limber jolt
#

DISCORD_BOT_TOKEN=TOKEN The =TOKEN I will replace with my real token But Im using a DOTENV and when I run It i get a error about how It thinks Its a str so It read NoneType

turbid condor
vernal moth
limber jolt
vernal moth
turbid condor
copper flume
#

nvm i got confused between you guys

red sparrow
#

when i use get_user

turbid condor
copper flume
#

and does the bot have member intents enabled

red sparrow
vernal moth
copper flume
#

good question

turbid condor
limber jolt
# turbid condor Can you show how you fetching it
import random
import os
from discord.ext import commands
from discord.ui import Select, View
import subprocess
import requests
import logging
from dotenv import load_dotenv


# Bot setup
load_dotenv()
logging.basicConfig(level=logging.INFO)``` And then to run It I have this after trying to debug ```try:
    bot.run(os.getenv('DISCORD_BOT_TOKEN'))
except discord.errors.LoginFailure as e:
    print(f"Error logging in: {e}")
except TypeError as e:
    print(f"Type Error: {e}")```
red sparrow
copper flume
vernal moth
#

give me a muint to test

copper flume
#

brother

red sparrow
copper flume
turbid condor
copper flume
limber jolt
red sparrow
#

the avatar is the error

limber jolt
copper flume
turbid condor
vernal moth
vernal moth
#

i added the print thing that u told me and i got same error

limber jolt
red sparrow
#

DONT SSHOW UR TOKEN

copper flume
vernal moth
turbid condor
#

It's almost full

copper flume
#

brainrot

limber jolt
copper flume
vernal moth
#

nah in the main folder

copper flume
#

try running the bot in local

#

check if it runs

turbid condor
vernal moth
limber jolt
turbid condor
vernal moth
copper flume
#

do you have firewalls?

vernal moth
copper flume
turbid condor
#

!pip dotenv-python

unkempt canyonBOT
#

Read .env(-ish) configuration file for python web applications.

Released on <t:1485617645:D>.

copper flume
#

ah no

vernal moth
turbid condor
#

Not this one

copper flume
#

why 443 is opened

limber jolt
turbid condor
#

!pip python-dotenv

unkempt canyonBOT
#

Read key-value pairs from a .env file and set them as environment variables

Released on <t:1705991580:D>.

turbid condor
red sparrow
#

what happen if i get rate limited

turbid condor
copper flume
#

i am not sure then, but i can say your code is okay and you have issue with RDP

red sparrow
turbid condor
red sparrow
#

a

turbid condor
#

Tho i doubt you will get rate limited if that's a small bot

limber jolt
turbid condor
limber jolt
turbid condor
#

pip uninstall dotenv-python

limber jolt
boreal sigil
#

how do i do that?

vernal moth
mild token
#

interaction.client do not have owner am i missing something? how can i check client owner? found myself

boreal sigil
#

@turbid condor can u help me with a bunch of stuff?

#

i need:
a basic mute cmd (the one i have atm is half done and super difficult)
to finish this reply cmd with the parameters i want
probs a bunch of other stuff but im focusing on this atm

carmine folio
#

Fuck discord its the worst platform fuck this shit
Goggle meet> discord

glossy flame
#

is it against discord tos to send messages in a specific server via my bot? for example, if i were to make it so that whatever i input to the console it sends to a channel in the server

slate swan
glossy flame
#

im in the server myself, but i just wanted to make sure it isnt against the rules to do so

rain hedge
glossy flame
#

its a personal server, so just as a gimmick

rain hedge
#

I would speak with the owner so they dont remove the bot.

#

But I dont think thats breaking tos

stoic tusk
midnight oracle
vital ore
turbid condor
limber jolt
#

Hello does anyone has atleast some Python coding skill and would like to make a bot with me?

mild token
#

from on_error how will i get the interaction paramter which user passed?

limber jolt
#

My bot IS not running

#

It wont print Its ready

#

And wont go online

mild token
finite salmon
#

What

#

wym

limber jolt
#

What Is that name

mild token
#

i want to know is there any method or property to get the paramter which application_command used at the time of invocation

finite salmon
limber jolt
finite salmon
#

Go to the docs and search for discord.Interaction and look at the list of attributes under it

finite salmon
mild token
mild token
finite salmon
finite salmon
#

You'll have to just pass in the commands parameters to the view's __init__ method and access it from there then

finite salmon
mild token
#

i remember earlier when there was just text command they have some property which tells that

finite salmon
#

There isn't any built in method of function for every little thing in dpy

#

You'll have to apply general python knowledge also

mild token
mild token
finite salmon
#

Even if any method like that exist, getting data from memory is much faster than from a request to an endpoint

mild token
finite salmon
#

Yes, I know

mild token
#

using property doesnt ping the api again all are injected in __init__ already and there are propeties defined to access it

finite salmon
#

You can bind it to the class instance and access it in the on_error

class Test(discord.ui.View):
    def __init__(self, param_name, *args):
        self.param_name = param_name
    async def on_error(self, interaction: discord.Interaction, error: Exception, item: discord.Item):
        print(self.param_name)
quick gust
#

I think you can do interaction.command.parameters, not sure if that's what ure looking for though

timber dragon
#

Not really, that's a View

quick gust
#

ah right, nvm

#

I thought they said commandtree or something

mild token
#

<Namespace player_tag='2ppppppp'> this is how u get the name and value of parameter

quick gust
#

Nice πŸ‘πŸΌ

solid turtle
#

lf for people to help me code like a team.

  • making any bot that we can think to come to mind
solid turtle
#

yo

#

any discord people active?

boreal sigil
#

One which is /reply

#

And it could be:
/reply <message ID to reply to> <what to reply with> <do you want to have reply mention true or false>

solid turtle
dense falcon
#

When using hybrid commands, is there any way to detect which way the command was used? I have a command that needs a file uploaded to work but since you cant upload files AND use slash commands, I need a way to detect if the slash command is being used and alert the user

timber dragon
#

there is a whole type attachments: annotate a param with discord.Attachment and discord will show a neat ui where users can upload a file

#

and ext.commands will also fill it in when a file is passed with the message

dense falcon
#

oh thats convenient

#

thanks

radiant shuttle
#

hello how the lists on the embed called, i mean the new funtion that you click and a list that you choose a selection appears

faint sapphire
#

possible to make a bot copy paste images?
such that, if the original gets deleted, the copied one remains.
so not like copy pasting the url/image link

finite salmon
faint sapphire
#

no way around that :/

boreal sigil
#

if u want context just see the replies to stuff

#

if any1 wants to help me just ping me ill be here

faint sapphire
#

I think message deletion is an event, so when u retrieve the content and theres an image, I wondered if its possible to simply send that image to another channel directly

faint sapphire
#

I mean multiple inputs

finite salmon
finite salmon
boreal sigil
faint sapphire
#

its so common theres prob an inf tutorials on it

boreal sigil
#

alr

turbid condor
boreal sigil
#

uuh

#

a bit - ive made some stuff

#
# SAY COMMAND
@commands.has_permissions(manage_messages=True)
@bot.hybrid_command()
async def say(ctx, message=None):
    """ Makes the bot speak """
    await ctx.send(message)
@say.error
async def say_error(ctx, error):
    if isinstance(error,commands.CheckFailure):
        await ctx.send('You do not have permission to use this command!')
    else: 
        raise error

made this

turbid condor
#

Ok good now this will be a hybrid command too i assume?

boreal sigil
#

yeah

#

made lock, unlock, hide, unhide, ban, unban

#

ping too

turbid condor
#

Ok now what you need to do first of all create the arguments in a function

#

namely

  • message_id : int
  • reply: str
  • flag : bool
#

You getting it?

boreal sigil
#

yeah to a degree

#

btw i love ur banner

turbid condor
#

Ok so tell me how the function decleration will look?

boreal sigil
#

so would that be the async def bit

turbid condor
#

Yes

boreal sigil
#
@commands.has_permissions(manage_messages=True)
@bot.hybrid_command()
async def reply(ctx, replymessage=None, message_id, flag):
    """ Makes the bot reply to a message """

this probs has like 15,000 errors

turbid condor
boreal sigil
#

!d type hint

unkempt canyonBOT
#

An annotation that specifies the expected type for a variable, a class attribute, or a function parameter or return value.

Type hints are optional and are not enforced by Python but they are useful to static type checkers. They can also aid IDEs with code completion and refactoring.

Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using typing.get_type_hints().

See typing and PEP 484, which describe this functionality.

boreal sigil
#

alr had to check what it was

#

so i gotta import typing

#

then what does one need to do?

turbid condor
boreal sigil
#

welp its not defined anywhere else

turbid condor
#

Ok I'll show you an example of what typehint looks like

async def reply(ctx:command.Context, id:int, message: str , flag: Literal["True","False"] = "True")```
#

This typehinting

boreal sigil
#

ahhk

#

got this so far

# REPLY COMMAND - IN PROGRESS!!
import typing
@commands.has_permissions(manage_messages=True)
@bot.hybrid_command()
async def reply(ctx:command.Context, id:int, message: str , flag: Literal["True","False"] = "True"):
    """ Makes the bot reply to a message """
    await ctx.reply(message)
@reply.error
async def reply_error(ctx, error):
    if isinstance(error,commands.CheckFailure):
        await ctx.send('You do not have permission to use this command!')
    else:
        raise error
turbid condor
#

Now first thing you need to do is get the guild object of where the command is used

boreal sigil
#

so would that be guild id or channel id or smth else

turbid condor
#

Then use get_message on that guild object using the id arg

turbid condor
boreal sigil
#

what is guild object just before we continue

quick gust
#

an object representing a guild

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a β€œserver” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
boreal sigil
#

ahhk

boreal sigil
turbid condor
#

Yes

#

But make sure to wrap id in int() function

quick gust
quick gust
turbid condor
boreal sigil
#

new goal: find out how tf i do this

quick gust
#

do what?

boreal sigil
#

continue

#

do get_message

#

stay alive

turbid condor
quick gust
boreal sigil
#

so now it'd be this then?

async def reply(ctx:command.Context, message_id:int, message: str , flag: Literal["True","False"] = "True"):
boreal sigil
#

actually

#

the first one

quick gust
#

alright so you'll also need the channel id then, or the ID of the member who sent the message you want to reply to

boreal sigil
#

so so message id

#

wait a min

#

id of the member or message?

quick gust
#

member who sent the messagee you want to reply to

boreal sigil
#

is there like a way to get the message author from the message ID

quick gust
boreal sigil
#

so if i want to reply to any message in any channel i need to get the authors id

quick gust
#

the author of the message that you are replying to

#

not the person who ran the command

boreal sigil
#

ok so how do i get that

quick gust
#

ask for it in the command arguments

boreal sigil
boreal sigil
quick gust
#

add another argument channel_id or author_id whatever u want

boreal sigil
quick gust
#

what does it say?

boreal sigil
#
async def reply(ctx:command.Context, message_id:int, message: str , flag: Literal["True","False"] = "True", author_id:int):
scarlet tiger
boreal sigil
#

oh so that goes at start

#

ahhhhhhh makes sense

quick gust
#

conventionally before message_id

boreal sigil
#

done

#

fixed and no errors (yet)

quick gust
#

Ok so now that you have the author id

boreal sigil
#

btw theres this too

quick gust
#

commands.Context

boreal sigil
#

ahhk

#

what next?

quick gust
#

also make sure to check if the ID is valid (member/msg will raise NotFound if its invalid)

turbid condor
quick gust
boreal sigil
#

hahah ok

quick gust
#

change your argument to author instead of author_id and typehint it to discord.Member

boreal sigil
#

ok

turbid condor
#

Wouldn't need to use get_member and is easier to mention the user then actually getting their id and then using that

boreal sigil
#

have this so far

quick gust
#

remove member = ...

#

you just need author.fetch_message now

boreal sigil
quick gust
#

i meant remove the whole line...

turbid condor
#

message = author.fetch_message(int(message_id))just use this

boreal sigil
#

oh rip

quick gust
boreal sigil
#

k

slate swan
#

await might be a good idea as well

turbid condor
#

!d discord.Member.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
turbid condor
#

Yeah a coro so await

boreal sigil
#

im stupid so i know this is not what yall meant but my brain cant handle tryna figure out what yall did mean

turbid condor
#

After equal sign

slate swan
#

How much of python/async do you know in the first place

quick gust
#

it's probably a good idea to learn python first

boreal sigil
#

this my first time using it for discord bots tho

slate swan
#

discord.py is not made for people who only know some of python and async

#

It's made for people with advanced knowledge

quick gust
#

I mean even someone with some knowledge would know how to await a coroutine

#

I have a feeling this is ur first time doing async

boreal sigil
#

i mean

#

ive done a few command bits

scarlet tiger
slate swan
#

There's a list somewhere which shows what you should know before jumping in

opal vortex
dense falcon
#

Is it possible to get the person who deleted a message? If they aren't the message author ofc

quick gust
#

check audit logs?

#

I haven't used em in a minute cant remember if it logs who deleted a message

boreal sigil
quick gust
#

If they aren't the message author ofc

dense falcon
quick gust
#

you can try to see if it appears in audit logs

#

idk any other workaround

dense falcon
#

alrighty

boreal sigil
west hare
#

Do you know how to edit original message from View? I'm making pagination
some minimal code:```py
class Pagination(ui.View):
def init(self: "Pagination", msgs: list[str], page: int) -> None:
super().init()
self.msgs = msgs
self.page = page
self.last_page = len(msgs)

@ui.button(label="Next", custom_id="pagination_next", style=ButtonStyle.blurple)
async def next(self: Self, interaction: Interaction, button: ui.Button) -> None:
    self.page += 1
    await interaction.edit_original_response(content=self.msgs[self.page], view=self)
and it called from slash command like that:```py
await interaction.response.send_message(msgs[page], view=Pagination(msgs=msgs, page=page), ephemeral=True, suppress_embeds=True)
#

This code currently can only send first message, but on button press it looks like show error from timeout

#

I've also tried```py
await interaction.message.edit(content=self.msgs[self.page], view=self)

turbid condor
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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

Responds to this interaction by editing the original message of a component or modal interaction.
west hare
turbid condor
spring rampart
#

what should i use to host my discord bot!?!?!?!?

#

idk if there are any free hosting things

#

but i kinda need that cuz im broke

fervent bloom
dim pond
dim pond
#

Np

#

Do anyone have a source code of discord bot (Python) I kinda need it you can give me any bot like moderator, fun or any category

flint parrot
digital hill
#

Hey, I'm working on a bot discord, however, I don't know how to display a json image url through my bot, like for example: "imageUrl": "my_image_path.jpg".

Any idea ?

limber jolt
#

My script Isnt working and idk why I try to load cogs but it dont work the cogs folder has my files with my stuff.

#

Aka that part of the bot

#

Im making diff files for other parts

#

Like fun ect

limber jolt
#

Please help

fast osprey
#

Code? Behavior?

limber jolt
fast osprey
#

I don't help in dm's personally

limber jolt
#

So

#

I have a cogs folder iwth my shift commands

#

Shift commands Is that link

#

!paste

#

!paste

#

Then thats my main bot.py but when I do any of the commands iN the first link It says they dont exist.

#
  bot.add_cog(Shift(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog: Extension 'cogs.shift' raised an error: TypeError: object NoneType can't be used in 'await' expression``` And thats the error I get when It prints error.
fast osprey
#

Adding cogs is async in dpy 2.0+ (and forks of it)

fast osprey
limber jolt
#

Not done this for awhile

fast osprey
#

If your existing code/knowledge was on a 1.x version and you are now on a 2.x version, there is a migration guide in the docs

limber jolt
timber dragon
#
  1. Make sure the setup func is async
  2. await add_cog
  3. await load_extension βœ…
limber jolt
#

cogs iS the folder Its iN

fast osprey
#

that's not what you pass into add_cog

#

do you know the difference between a cog and an extension?

fast osprey
#

The two sections in the docs for each explain it well

#

but a lot of people use the term "cog" erroneously to refer to extensions

ember nest
#

Anyone here have made money by bot development? Dm me I got few questions

digital hill
#

Hey, I'm working on a bot discord, however, I don't know how to display a json image url through my bot, like for example: "imageUrl": "my_image_path.jpg".

Any idea ?

slate swan
#

Hello! I am making a Discord bot, and I am trying to make it where it gets a list from a JSON file and loops through it for specific keywords that have a specific "theme". I store the words into a list and basically sort through them. However, for some freaking reason, the list gets cleared when it is done getting sorted (inside of a for loop), and I end up getting an IndexError. Can anyone help out? Thank you!!!

Code

What a "word" looks like

{
  "content": "example",
  "theme": "randomtheme",
  "level": 5
}

For loop

def return_new_word(selected_theme: str) -> str:
    words: list = []
    sus_words: list = loads(open('data/dict/sus_words.json').read())

    for word in sus_words:
        if word['theme'] == selected_theme and not word['theme'] == 'target':
            words.append(word['content'])
        elif word['theme'] == 'target':
            for guild in client.guilds:
                for member in guild.members:
                    words.append(member.name)
                    break

    return choice(words)  # This is where the error occurs
idle vault
fast osprey
slate swan
midnight oracle
#

What was it? I'm curious

stray linden
#

dang i wish this was higher in the list

#

imma make a mod bot

limber jolt
solid turtle
#

someone said a selfbot is dangerous den a bot

#

can anyone tell me why

turbid condor
#

Then if the self.bot has permissions it can mess up your server real good since user acc has different rate limits then bots

solid turtle
#

but bots still can mess up ur server

#

dm on rate limits I made a bot that can bypass this bot called "security bot" for testing purposes

#

it took the bot 2 seconds to ban it while it took my bot 1.86 to delete the channels and ban 95/150 people.

#

theoretically

timber dragon
#

Weird flex but ok

solid turtle
limber jolt
#

over the past few hours i've added like 4-5 other files with fun and moderation commands but only the commands from shift.py work I've made sure to laod them all.

fast osprey
#

Code?

vocal locust
#

Do somoene know what video can help me to create an dashboard on discord.py?

#

Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?Do somoene know what video can help me to create an dashboard on discord.py?

tiny creek
#

Spamming won't help anyone!

fast osprey
#

You also should not be looking for videos to teach you non visual concepts. There's a lot at play here, you will want to read articles to know how to do these things individually then tie them together rather than solely looking for one thing that tells you how to do this exact combination of them. Those "tutorials" more often than not are extremely low quality and just throw bad code at you without teaching you anything about the choices being made

dire loom
#

And you won't learn anything by watching a video. You aren't a visual learner, regardless of what you say.

boreal sigil
#

hey so I made some code for a command that sends a button menu kinda thing but the colours arent working.

class Menu(discord.ui.View):
    def _init_(self):
        super()._init_()
        self.value = None
class SimpleView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=30)  # times out after 30 seconds
        rulesbutton = discord.ui.Button(label='Read the Rules', style=discord.ButtonStyle.url, url='https://discord.com/channels/1237815910887194624/1239284848057651391', emoji='β›”', color=0xff0000)
        self.add_item(rulesbutton)
        rolesbutton = discord.ui.Button(label='Self Roles', style=discord.ButtonStyle.url, url='https://discord.com/channels/1237815910887194624/1237826995941806231', emoji='πŸ’»', color=0x00b6ff)
        self.add_item(rolesbutton)
        colorbutton = discord.ui.Button(label='Name Colour', style=discord.ButtonStyle.url, url='https://discord.com/channels/1237815910887194624/1237827021137248287', emoji='🌈', color=0xf100ff)
        self.add_item(colorbutton)
        ticketbutton = discord.ui.Button(label='Help and Support', style=discord.ButtonStyle.url, url='https://discord.com/channels/1237815910887194624/1237874844595654707', emoji='🎫', color=0xfff700)
        self.add_item(ticketbutton)
        infobutton = discord.ui.Button(label='General Info', style=discord.ButtonStyle.url, url='https://discord.com/channels/1237815910887194624/1246832229003558932', emoji='πŸ“œ', color=0x00ff59)
        self.add_item(infobutton)

@bot.command() 
async def button(ctx):
    welcome = discord.Embed(title = f"Heya, {ctx.author.display_name}, welcome to The Pikachu Crew!", description = f"Welcome to The Pikachu Crew. I hope you enjoy your time here! Please use the buttons below to navigate to useful channels.")
    await ctx.send(embed=welcome, view=SimpleView()) 
#

ik the bot.command bit doesnt make sense but im just putting it as a bot command before i make it into a welcome message

fast osprey
#

url buttons have a consistent style

#

You can't change their color

boreal sigil
#

oh

#

how can i make buttons that take you to a certain channel, have an emoji and have a color

turbid condor
boreal sigil
#

is there an alternative to a url button that still can take you to a channel?

turbid condor
#

You can use hyperlinks

boreal sigil
#

ooo

turbid condor
boreal sigil
#

so put those as the text then?

turbid condor
#

Yes

boreal sigil
#

would I change style=discord.ButtonStyle.url to style=discord.ButtonStyle.text

turbid condor
#

It's just text

#

As in content of a message

boreal sigil
#

so do i keep style=discord.ButtonStyle.url as it is?

timber dragon
#

Yeah else it will error

#

There is ButtonStyle.text even

boreal sigil
#

so i keep style=discord.ButtonStyle.url?

timber dragon
#

Yes.

boreal sigil
#

ok

timber dragon
boreal sigil
#

thanks it wasnt very clear lol

timber dragon
#

Discord renders urls and stuff

boreal sigil
#

ik

#

i wanted it to look cooler

timber dragon
#

Fair

boreal sigil
#

and also learning curve

boreal sigil
# timber dragon Fair

so its now going to be smth like this?

        rulesbutton = discord.ui.Button(label='[Read the Rules](https://discord.com/channels/1237815910887194624/1239284848057651391)', style=discord.ButtonStyle.url, emoji='β›”', color=0xff0000)
        self.add_item(rulesbutton)
turbid condor
#

No

#

Look in here how to make buttons

timber dragon
#

You cannot use markdown on the label

boreal sigil
#

so its now going to be smth like this?

        rulesbutton = discord.ui.Button(url='[Read the Rules](https://discord.com/channels/1237815910887194624/1239284848057651391)', style=discord.ButtonStyle.url, emoji='β›”', color=0xff0000)
        self.add_item(rulesbutton)
patent hull
#

url is an url

#

you can just put the "Read the Rules" text in label

timber dragon
#

^ you want label="read the rules" and url="the url here"

#

WITH the style and optional emoji

#

Oh and you cannot change the color of the button lol

#

Neither can you set a custom color

boreal sigil
#

wait so even with markdown i cant change the colour?

fast osprey
#

URL buttons have a consistent ui

stoic tusk
#

someone knows how to make the presence intent thingy for when someone updates / has a specific status they will receive a role and an embed messages in dms?

#

i need it for a server im working on and idk how to do it

stoic tusk
#

that thing, idk to set it up so I decided I should ask someone in here

#

tut video or something

fast osprey
#

You should not look for videos, they are notoriously bad and not a good medium for conveying this information.

That said, there is an event for on_presence_update, though you should be careful about dming people especially if they have no opted into it

wheat thunder
#

Does anyone have a good example about slash command in cog?

#

I want to update my old command to slash command

slim bloom
turbid condor
wheat thunder
#

but ty for help

#

lol

turbid condor
primal valve
#

guys, for my next project I want to make a discord bot, do yall know any cheap and good hosting ?

#

I mean, think I have lot of time for that, but I was just wondering

wheat thunder
#

/sauce

-> Select between 2 choices:

  • with index
  • without index

If "with index" is selected -> input index (int) required.
Else (if "without index" is selected) -> index defaults to 0.

I'd like to implement this type of slash command, could you give me some advice??