#discord-bots

1 messages · Page 336 of 1

hushed galleon
#

dynamic cooldown only provides an interaction to your factory callback, not self, so you'll need to rewrite it another way

#

given that is_premium only really needs the bot, i suggest turning it into a regular function and accessing bot from the interaction with interaction.client

#

e.g. ```py
async def premium_cooldown(interaction: discord.Interaction) -> app_commands.Cooldown:
bot = interaction.client
...

in your cog:

@app_commands.command()
@app_commands.checks.dynamic_cooldown(premium_cooldown)```
graceful ermine
hushed galleon
#

interaction.client is whatever bot instance is receiving the interaction, and i'd assume you only have one bot instance that you've been using across your code

vapid parcel
#

So i have a file called cog_setup1.py inside of a folder called commands, which does all cogs n stuff, the in my Bot.py file i just load the cog_setup1. How could I restart the cogs? I have tried restarting it before, but then it says my cogs are already loaded. I am wondering how I can do that?

If that doesn't explain it well, here is what I mean, this Ticket system I made kinda explains what I mean.

https://github.com/RejectModderss/TicketSystem

GitHub

Discord Ticket System made in Discord.py. Contribute to RejectModderss/TicketSystem development by creating an account on GitHub.

hushed galleon
unkempt canyonBOT
#

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

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension) followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension) except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
hushed galleon
#

oh wait, not sure if discord.py can tell where the cogs came from...

#

doesn't have to be bot.py, you can call that function wherever you want

vapid parcel
#

Its saying the cogs are already loaded.

#

meaning it didn't unload them clearly when its supposed to

hushed galleon
#

hmm yeah, it needs to be reorganized as an actual package

vapid parcel
#

So how can I do that?

#

I only know cogs as this way tbh

hushed galleon
vapid parcel
#

Okay thank you so much it worked 😭

#

You are a god 😭

hushed galleon
#

you can also check the source code for more details, but essentially it only recognizes cogs to unload if either:

  1. your extension is a module (a .py file) and the cogs are defined inside that module;
  2. your extension is a package (__init__.py) and the cog is defined in init or a submodule
unkempt canyonBOT
#

discord/ext/commands/bot.py lines 885 to 890

async def _remove_module_references(self, name: str) -> None:
    # find all references to the module
    # remove the cogs registered from the module
    for cogname, cog in self.__cogs.copy().items():
        if _is_submodule(name, cog.__module__):
            await self.remove_cog(cogname)```
old vine
#

how to get the day that the bot joined the server.

vapid parcel
#

It worked, but that was such a simple fix man

old vine
vapid parcel
#

you are a legend

#

Everyone else would say like, use reload kinda like you said, even tho I showed them what I was talking about, because that wasn't gonna work, then they would say yes it would. But it clearly didn't but you are like the only one who sat there n explained it

hushed galleon
frail perch
#

Hello! Is it possible to embed/attach an image to discord thread post via api? Couldn't find it in the documentation for discord.py

hushed galleon
frail perch
#

Thank you! I'll look into it right away

robust fulcrum
#

Wdym?

#

Maybe you are looking for

pip list
candid flume
#

i need to send messages to multiple channels, i've tried looping over an array of channel id's but it will only send a message to the last object in the list

@tasks.loop(seconds=3)
async def sendMessage():
    try:
        with open('utils/config/channels.json', 'r') as f:
            channels = json.load(f)
        for channel in channels:
            c = durere.get_channel(channel)
            await c.send('test')
            print(channel)

            
        print(f'sent message to: {c.name}')
    except Exception as e:
        print(e)
[
    1186639720397656805,
    1186719615569941656
]
nova hawk
#

icationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]

what does this mean?

pale zenith
hushed galleon
harsh orbit
#

there is some kind of bots that you can insert an bot token in it then the bot that you inserted its token will work in a certin project or code
does anyone has an idea how this thing work?

sick birch
cold sonnet
#

robin

#

what programming abilities does one have who has made an insane amount of discord bots

#

I dunno what to write in my resume

#

I just have
Python:
oop
asyncio
APIs

harsh orbit
#

also, can you give example pls?

sick birch
cold sonnet
#

maybe

sick birch
#

one token = one bot

harsh orbit
harsh orbit
#

I think you didnot understand me

#

the that I talking about its called 'bot maker' you just select the bot will work in wich code then in a modal just insert the token and the prefix and the bot will work immeditly

sick birch
#

it's like, basically the same as @novel apex . just put in your token and it works

harsh orbit
#

not in modal and chose the prefix also in modal

shrewd apex
sick birch
shy ledge
#

How can i make slash commands in replit?

slate swan
#

anyone know how to fix..

somber sky
#

im trying to make a command so basically you run a command and put a number, that number goes into a list with the server id so that it saves, but im having 2 different problems, #1 is that every time that a server runs the command multiple times it will give adding on to the list but i wanna make it where if the same server runs it multiple times then instead of keep adding on to the list it just updates and whatever number they put will change. and my other problem is i have a command to check the number to make sure that everytime the bot turns off the number saves but every single time that the bot restarts and i check, it just says 0 but it does stay in the list.

So basically, the number does store into the json file but if i do it twice then it adds on twice which i dont want and when i run the get command it will tell me the number right if i dont restart the bot but if i restart the bot and try it itll say 0.

somber sky
sick birch
slate swan
#

is there a way to only have your bot listen to whitelisted users?

somber sky
#

it goes into the list but when i run the get command it just says 0 idk why

sick birch
#

does the json file get updated properly?

#

try

RC.get(str(ctx.guild.id), 0)

in the get function

somber sky
#

alr let me try

#

oh it wont

#

worked*

#

thanks didnt know it was that easy 💀

somber sky
# somber sky i fixed the part where it added twice, but when i run the command if i restart t...

wait 1 question, so I kinda fixed it but not fully apparantly, so basically if i run the command multiple times and keep switching it wont add onto the list it just updates. BUT if i set a number and then restart the bot and then set a number again on the same server THEN it adds onto the list twice, how do I make it where reagrdless if i restart the bot or not it doesn't add the same server twice and it just updates

slate swan
#

TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print("Sharp is ready.")
    print("-----------------------")

@client.command()
async def hello(ctx):
    await ctx.send("hello boss.")
#

someone please tell me

#

what im doing wrong 😭

tidal spoke
#

when you declare client, you aren't declaring what intents you need. the commands.bot requires it. Here is how it traditionally looks:

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

slate swan
#

is there an easy way to make your bot user whitelist only?
or is it a fair amount of lines to code

slate swan
polar slate
#

am I getting trolled ?

tidal spoke
#

just try "rank_level"?

polar slate
#

Same

#

i didn't rename the .txt tho

tidal spoke
#

that should work

#

what are you doing python?

polar slate
#

You want to see the code ?

tidal spoke
#

um just send me a screenshot of the directory where your file sits

polar slate
tidal spoke
#

and this error is from your main or leveling?

#

oh its in leveling

polar slate
#

yeah

#

but I got a problem, when I execute the program

#

it put the DB on python

#

so maybe that's why

#

python is the sub directory

#

Okay it was that but now idk how to execute it in the bot_discord directory can someone help ?

final iron
#

!d discord.ext.commands.Bot.check

unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError).

Example...
slate swan
final iron
#

Anywhere

slate swan
#

ykw

#

im already confused ill think ill just stick to the very basics for now 😭

somber sky
#

im trying to make a command where when i put a server id it puts it in a list, but it dont work, what am i doing wrong?

async def whitelist(ctx, server_id: int):
  if server_id not in f.whitelistedservers:
      f.whitelistedservers.append(server_id)
      print(f'Added {server_id} to whitelistedservers: {f}')
      await ctx.response.send_message(f'{server_id} has been whitelisted.')
  else:
      await ctx.response.send_message(f'{server_id} is already in the whitelist.')```
latent pier
#

What is it showing? @somber sky

somber sky
#

theres no error it just doesnt go into the list

latent pier
#

Looks fine to me

somber sky
#

this is me testing

#

stays the same

final iron
#

That not how python works

#

It's not going to change your actual code

latent pier
#

Did you run command again with same id after adding it?

somber sky
#

yes

final iron
#

???

#

Are you expecting it to change your code?

latent pier
#

You won't see changes in code

somber sky
somber sky
final iron
#

Okay, but you're showing the code and saying it's not changing

#

It'll be changed in memory, so you'll need to print it to see the changes take effect

somber sky
#

wdym

polar slate
#

broke all my code

graceful ermine
#

Hey for some reason when I'm syncing my commands after loading my cogs, it doesn't sync but registers into other servers that the bot is in.

#
@bot.tree.command(name="sync", description="sync a command", guild=discord.Object(id=1197312375301345280))
@app_commands.checks.has_role('*')
async def sync(interaction: discord.Interaction):
    await interaction.response.send_message("commands should be synced", ephemeral=True)

    await bot.tree.sync()

    await bot.tree.sync(guild=discord.Object(1197312375301345280))

    await interaction.response.send_message("commands should be synced", ephemeral=True)
somber sky
queen pond
#

are discord bots a good way to improve my python knowledge(im somewhere between beginner and intermediate), would it be helpful if i wanna continue down the path as a software engineer?

pale zenith
#

The discord.py library is really nice and easy/comprehensive, so it's easy to grasp and learn

#

but creating complex features that require working around the niches and caveats of an asyncio app is a decent learning curve (ish)

queen pond
#

since idk about bots ig i'll start with something easier then try making more complex bots, thanks for the answer

polar slate
#

Hey member.add_role(userID, roleID) works right ?

#

because idk why when the bot try to asign the role it tells me the role is not existing

pale zenith
#

you need to pass in an actual role object, and the method is called add_roles

member = guild.get_member(1234)
role = guild.get_role(1234)
# Check if any of those are None or something...?
await member.add_roles(role)
polar slate
#

it will only work for one server then ?

#
async def level_role(member, lvl):
    with open("rank_level.txt", "r") as f:
        if lvl == 5:
            role = f.readlines(1)
            await member.add_roles(role)
        if lvl % 10 == 0:
            role = f.readlines(int((lvl / 10) + 1))
            await member.add_roles(role)

So my .txt with all my ID is useless ?

leaden jasper
polar slate
#

oka

leaden jasper
#

he said make a variable

role = guild.get_role(1234)

before doing


            await member.add_roles(role)
leaden jasper
#

not really clean but should work

polar slate
#

ok I need to pass guild then

#

idk how to get it

leaden jasper
#

maybe member has it

hushed galleon
# polar slate idk how to get it

technically add_roles() can accept a generic discord.Object, so you really only need the member object and the ID: py await member.add_roles(discord.Object(1234))

polar slate
#

i'll check it tomorrow am tired

unreal pilot
#

Tho i recommend get guild

unreal pilot
polar slate
reef mirage
#

Faced recently an issue, bot works create but after a time gets timeout and stop working, created new token worked and same issue happened again.

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

For this code part:

@channel.sub_command()
async def buttons(inter, channel: disnake.TextChannel):
    if inter.author.bot:
        return

    await inter.response.defer(with_message=True, ephemeral=True)

    view = disnake.ui.View()

The problem was- when the bot got into having this problem - scraping most of the code, and just had the: "await inter.response.defer(with_message=True, ephemeral=True)" and an output in the bot log, nothing happend and it timed out even by that .
creating a whole new bot - cloning the code project, and it was working again. until bot was invited to server a few days later and having it run for a couple of hours first time, the problem occured again and restart of the bot didn't fix it. only creating a new bot worked.

polar slate
unreal pilot
unreal pilot
#

so bot.get_guild(guild_id)

polar slate
#

Client*

#

I have to import everything in my second file then ?

unreal pilot
#

discord.ext.bot is a subclass of client but with more featuers

polar slate
#

why ? I made everything with client

unreal pilot
#

youre not reading what im saying

#

its a subclass, so it has everything, except its a generally improved and more extensive version of Client

polar slate
#

I am reading just wrote it as the time you sent the message xD

#

okay so i'll recode everything...

#

but I have to put bot = discord.bot(intents=intents) in every file I make ?

shrewd apex
#

no

simple surge
simple surge
frail perch
#

Hey! I'm losing my mind over 2 things:

  1. Forum Topic Tags are not working on my new version of the code.

  2. embedded url for topic image only works when manually setting it. Bot will not grab the right thing from api.

I have attached a link for both codes with a sample api response as well.
https://paste.pythondiscord.com/ORUQ
https://paste.pythondiscord.com/AYKQ

In an ideal world the script would add tags correctly from the database and also embedd and image for the post

hushed galleon
frail perch
#

I would love to not do this myself but as a startup it's tight right now

polar slate
polar slate
shrewd apex
#

u need to use cogs

polar slate
#

Ok I'll check about it I have a video in a playlist I watch about making bot

shrewd apex
shrewd apex
hushed galleon
polar slate
shrewd apex
#

u would also need to load the cogs for which u can check cogs page oh how that works

hushed galleon
# frail perch I modified the tag id's to protect myself before posting here. About the built-i...

as a sidenote, requests is a blocking library and will momentarily interrupt your bot while it waits for responses so if you're doing frequent requests, httpx or aiohttp would be more optimal: ```py
import aiohttp

async def make_request():
async with aiohttp.ClientSession() as session:
async with session.get(url, params=..., headers=...) as response:
data = await response.json()

...``` (aiohttp is what discord.py already uses)
frail perch
hushed galleon
#

oh, if not row['field_4804']: would be false though

simple surge
# polar slate I don't want a command prefix I only want to make /commands

Ahh I see, here's how I do my commands

import discord
from discord import app_commands 

guild_id = 1234

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.all())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=guild_id))
            self.synced = True

client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(guild = discord.Object(id=guild_id), name = 'test', description='...')
async def test(interaction: discord.Interaction):
    await interaction.response.send_message(f"test", ephemeral = True) 

client.run('token')
hushed galleon
#

commands.Bot still offers the cogs/extensions system which interoperates with slash commands fairly well, it's just somewhat annoying that dpy still requires the command_prefix= parameter...

polar slate
#

cant look at it RN

unreal pilot
unreal pilot
#

just add a regular bot.command that works with your prefix

#

to sync instead

unreal pilot
hushed galleon
simple surge
#

They are a slash command, only way it's actually synced is if it's ran in the proper guild.

unreal pilot
unreal pilot
#

and why sync if there's no command changes?

#

for bot development you'll do a lot of relaunches in which you dont necessarily edit command parameters

hushed galleon
simple surge
unreal pilot
#

that syncing to the tree on launch is unnecessary and nooby

simple surge
#

There is stuff for on_ready 🤷

vocal plover
#

and using a prefix command to sync it is clunky

unreal pilot
simple surge
vocal plover
#

how on earth are you gonna say that using a prefix command to sync things designed to remove prefix commands is not clunky lol

unreal pilot
#

youre not gonna win this argument

next oracle
#

I am looking for coding a discord bot

unreal pilot
#

its bad and nooby practice to include automatic tree syncing in on_ready

simple surge
hushed galleon
vocal plover
#

true, on_connect is better

unreal pilot
simple surge
next oracle
#

I dont use discord since I forgot my old discord accounts password but I make bots for a website called hack.chat and I think it is simillar to hack.chat

unreal pilot
#

that is not a good thing

simple surge
vocal plover
#

unless you're paid to make discord bots, not wasting your time fixing stuff that works absolutely is a good thing

simple surge
#

You definitely make some garbage bots m8..

next oracle
#

Who me?

unreal pilot
#

because i teach you something that is better practice i make garbage bots

vocal plover
#

not you

simple surge
next oracle
#

You guys really should use Mentions

#

or reply

unreal pilot
#

Clearly you got yourselves hired by a 14 year old for a failed stock replica

simple surge
unreal pilot
#

im not bashing you

#

im bashing your practice

#

because its a nooby practice

simple surge
unreal pilot
#

remember tango

next oracle
#

😭

unreal pilot
#

bro what the fuck is that code

next oracle
#

WDYM

#

its for hack.chat it works

unreal pilot
#

outrageous

simple surge
next oracle
#

@unreal pilot how iss this outrageous

unreal pilot
#

if you dont know that then youre not ready to develop with discordpy sorry

#

discordpy is a complicated library

next oracle
#

pOGO

vocal plover
next oracle
#

I am going to come back here and show you

#

You are going to regret saying that

unreal pilot
simple surge
slate swan
simple surge
vocal plover
#

If making bots is why you wanna get into programming make bots. Yes, it's complex, but it's hardly gonna be fun to make stuff you don't care about. Plenty of people have got into development through Discord bots, and it's not our place to tell them they're not worthy of it. I suggest either helping and encouraging, or staying out of it, because convincing beginners that they're not good enough to do the thing inspiring them to develop isn't cool

unreal pilot
unreal pilot
simple surge
unreal pilot
#

noi i didnt

#

i said it is nooby practice lol

simple surge
#

That's the same thing 💀

slate swan
simple surge
vocal plover
#

I'm really struggling to see how syncing upon startup is so terrible honestly, if it were a PUT request overwriting all commands then yeah, I'd understand, but as it is, just GETting all your commands, diffing, and updating ones that are needed is entirely reasonable, sensible even. There's a reason the ratelimit on GET commands is lower than POST/PATCH (or maybe it's PUT I can't remember), and that's because it's an inexpensive operation, which makes it suitable for that sort of use on startup

next oracle
#

How do I get a discord bot token?

slate swan
simple surge
next oracle
#

Is it free?

slate swan
#

Yes

unreal pilot
#

Seperate utils, database operations, blockchain operations.. you name it

#

keep cogs purely for discord comms and handle your more complex logic in seperate funcs

next oracle
#

is it application id Or public key?

slate swan
#

That’s not the bots token

next oracle
#

where do I get it?

sick birch
next oracle
#

Nvm found it

slate swan
next oracle
simple surge
#

What's your opinion on the way it's synced?

unreal pilot
next oracle
#

Uh

#

I made the bot and ran the code

unreal pilot
#

Code organisation is so important for discord bots

next oracle
#

How do i add it to a server

#

2024-01-18 15:26:15 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-01-18 15:26:15 INFO discord.client logging in using static token
2024-01-18 15:26:16 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 30742bfa6c1cbf519a9dd16cd25dfe1a).
Logged in as IntelliBot

naive briar
#

How severe is the rate limit for syncing? I don't think it even matters how you sync if you're not doing it hundreds of time in a single minute 🥴

simple surge
next oracle
#

ok

next oracle
#

now wut

slate swan
#

Restart the bot

next oracle
#

ok

unreal pilot
#

I dont understand helping somebody when he doesnt understand the reason behind the actions

#

You wont learn anything then

next oracle
#

2024-01-18 15:30:41 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-01-18 15:30:41 INFO discord.client logging in using static token
2024-01-18 15:30:42 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 56025b8dfc9093e7122585e83aa3c450).
Logged in as IntelliBot

naive briar
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.

next oracle
#

it did nothing even reset the token

unreal pilot
#

See what i mean

naive briar
next oracle
#

oh thank you @naive briar

naive briar
#

If someone actually doesn't try, then that's another problem

next oracle
simple surge
next oracle
#

import discord
from discord.ext import commands
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)

intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
intents.reactions = True

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

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
await bot.change_presence(activity=discord.Game(name='Type !help'))

@bot.command(name='hello', help='Responds with Hello!')
async def hello(ctx):
"""Greets the user."""
await ctx.send(f'Hello, {ctx.author.mention}!')

@bot.command(name='ping', help='Check the bot's latency')
async def ping(ctx):
"""Check the bot's latency."""
latency = round(bot.latency * 1000)
await ctx.send(f'Pong! Latency is {latency}ms')

@bot.command(name='clear', help='Clear messages in the channel')
async def clear(ctx, amount: int):
"""Clear messages in the channel."""
if 1 <= amount <= 100:
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f'{amount} messages cleared by {ctx.author.mention}.', delete_after=5)
else:
await ctx.send('Please provide a number between 1 and 100.')

bot.run(' ')

#

I used a template

#

I think its good

#

it keeps saying no privlegges

slate swan
#

in the screenshot I posted

#

He shouldn't expect to be spoonfed, that's not how you learn

next oracle
#

I fixed it

#

Now how do i add it to a server

slate swan
#

Nvm I misread what you sent

slate swan
#

Select the permission your bot needs'

next oracle
#

thx

#

LETS GO

unreal pilot
vocal plover
#

then stay out of it /shrug, not your place to be telling others who not to help if they want to help

next oracle
#

Thank you guys so much I made my first bot it isnt the best but atleast I did it thank you guys so much

slate swan
#

is it possible to make it so no matter what perm level you have youre able to use commands like ban, kick etc with your bot?

slate swan
#

the bot has admin and is at the top of the roles list and i would just be a member with no permissions

slate swan
#

On the bots end

vocal plover
#

you can, but speaking as a community manager if I found out a bot's owner was going around banning people through their bot even in servers they don't moderate I'd kick the bot and warn everyone I knew not to use it immediately, you shouldn't be claiming jurisdiction over other people's servers like that

next oracle
slate swan
next oracle
# slate swan I would only be using it on servers i run/manage incase i was talking on an alt ...
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

# You can change these if youd like
PERM_LEVEL_ADMIN = 2
PERM_LEVEL_MODERATOR = 1
PERM_LEVEL_USER = 0

def check_permission_level(ctx, required_level):
    user_permissions = {'admin_user_id_1': PERM_LEVEL_ADMIN, 'moderator_user_id_2': PERM_LEVEL_MODERATOR, 'regular_user_id_3': PERM_LEVEL_USER}
    user_permission_level = user_permissions.get(str(ctx.author.id), PERM_LEVEL_USER)
    return user_permission_level >= required_level

@bot.command(name='ban', help='Ban a member (custom permission check)')
async def ban(ctx, member: discord.Member, reason=None):
    if check_permission_level(ctx, PERM_LEVEL_MODERATOR):
        await member.ban(reason=reason)
        await ctx.send(f'{member.mention} has been banned. Reason: {reason}')
    else:
        await ctx.send('Permission denied.')

@bot.command(name='kick', help='Kick a member (custom permission check)')
async def kick(ctx, member: discord.Member, reason=None):
    if check_permission_level(ctx, PERM_LEVEL_MODERATOR):
        await member.kick(reason=reason)
        await ctx.send(f'{member.mention} has been kicked. Reason: {reason}')
    else:
        await ctx.send('Permission denied.') #firth thene add anything else youd like ```
#

Please do not try backdooring any servers using this

slate swan
next oracle
#

Then just add bot.run('Your token')

#

Its not the best code I also used some templates to help me so I didnt do all of it

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

next oracle
hushed galleon
#

not that significant even if you do get throttled, so i guess setup_hook is okay enough for syncing

next oracle
#

I feel like a douche

#

I have covid and im just sleeping on my bed all day and codingn

simple surge
next oracle
#

My old account

#

Password gone

frail perch
#

Uff, using the new ForumChannel.create_thread() method however discord answers with '''Failed to create forum thread. Error: 400 Bad Request (error code: 50006): Cannot send an empty message
Failed to post the topic.''' code: https://paste.pythondiscord.com/JEMA

vocal plover
#

also as general improvements, you can apply tags while creating the thread by passing them into the applied_tags arg of the create_thread call, so you don't need a separate API call afterwards

frail perch
vocal plover
#

what are you passing to it? have you read the docs for what needs to be given to it?

#

!d discord.ForumChannel.create_thread

unkempt canyonBOT
#
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, content=None, tts=False, embed=..., embeds=..., file=..., files=..., stickers=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this forum.

This thread is a public thread with the initial message given. Currently in order to start a thread in this forum, the user needs [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages).

You must send at least one of `content`, `embed`, `embeds`, `file`, `files`, or `view` to create a thread in a forum, since forum channels must have a starter message.
vocal plover
#

It seems like you're passing either content or embeds, but trying to provide it as message= when it should be embeds=[] or content="..."

frail perch
#

Oh, fixed it. Now only image url has to be passed, but it seems to stay empty ```async def create_forum_thread(channel_id, name, message, image_url=None, tag_ids=None):
channel = bot.get_channel(int(channel_id))
if not channel or not isinstance(channel, discord.ForumChannel):
print(f"Channel {channel_id} is not a ForumChannel or not found.")
return False

try:
    # Prepare the embed with the image (if provided)
    embed = None
    if image_url:
        embed = discord.Embed(description=message)
        embed.set_image(url=image_url)

    # Create a thread with the initial message and/or embed
    thread = await channel.create_thread(
        name=name, 
        auto_archive_duration=10080, 
        content=message if not embed else None, 
        embed=embed
    )

    # Apply tags to the thread if they exist
    if tag_ids:
        tag_objects = [discord.Object(id=tag_id) for tag_id in tag_ids]
        await thread.edit(applied_tags=tag_objects)

    return True
except Exception as e:
    print(f"Failed to create forum thread. Error: {e}")
    return False```
#

everything else comes through

#
In message.embeds.0.image.url: Not a well formed URL.
Failed to post the topic.```
frail perch
#

could it be (url=image_url) not getting handeled correctly?

unreal pilot
#

use
```py
#code here
```

#

this is unreadible with no formatting

frail perch
#

as at the start of the script when printing it gets returned correctly

#

thank you @unreal pilot ! ```smiley

slate swan
#

im making a logger that logs every message with my bot

#

how do i make it ignore certain channels/categories/members/servers?

#
@bot.event
async def on_message(message):
    channel = bot.get_channel(1197588840421019748)
    await channel.send("{} in {}: {}".format(str(message.author), message.guild.name, message.content))

this is what i have, i just want it to ignore this channel id (1197588840421019748)

pale zenith
slate swan
slate swan
#

currently trying to make a command that clears 500 of my messages but im not sure how to filter it to only clear my messages

@bot.command()
async def m(ctx, amount: int = 500):
    if ctx.message.author.id == firthid:
        await ctx.channel.purge(limit=amount+1)
    else:
        return
#

is there like a way to check if the message is sent by a certain id

bronze remnant
#

@tree.command(name='change_avatar', description='Change The Profile Picture Of The Discord Bot', guild=discord.Object(id=server_id))
async def change_avatar(interaction, url_of_image: str):
await client.user.edit(avatar=url_of_image)
embed = discord.Embed(title='Successfully Changed Avatar', color=discord.Color.blue()).set_thumbnail(url=url_of_image)
await interaction.response.send_message(embed=embed)

when i execute the command i get the error

discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'change_avatar' raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes

can someone help?

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
sick birch
#

note the check= kwarg

#

accepts a callable that has a Message object as its input and a Boolean as its output

formal basin
#
2024-01-18 18:55:35 ERROR    discord.client Attempting a reconnect in 0.20s
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

``` why is it reconnecting?
slate swan
#

like that?

vale flint
#

does any1 have a slash command discord bot template

sick birch
slate swan
#

firthid = 719211519359058070

#

which im guessing is not how check works

sick birch
sick birch
vale flint
#

thanks

slate swan
#

im not really sure how to code that and ive searched it on google and i cant get anything

vale flint
#
import discord
from discord_slash import SlashCommand

client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) 

@client.event
async def on_ready():
    print("Ready!")

client.run('')
#

error:
from discord_slash import SlashCommand # Importing the newly installed library.
ModuleNotFoundError: No module named 'discord_slash'

#

how do i fix it, i've tried everything

sick birch
#

personally since it's just a really simple one line function I'd just do a lambda but you don't have to

somber sky
#

I have this command where badically what it does is where every single server has there own RC which is just a number, if a server runs the command twice instead of adding that number onto the list, it just updates it since the server ran it 2 times. But the problem I am having is that every single time that the bot restarts and a server who already did the command does it again, it adds on to the list instead of updating the list

#

so basically what im trying to do is regardless if i restart the bot or not, in my list there should not be 2 of the same id's, it should just update it

slate swan
# sick birch sure, that sounds like one way
@bot.command()
async def firth(ctx, amount: int = 500):
    if not ctx.message.author.id == firthid:
        return 
    to_delete = []
    async for m in ctx.channel.history(limit=amount+1):
        if m.author.id == firthid:
            to_delete.append(m)
        if len(to_delete)==100:
            await ctx.channel.delete_messages(to_delete)
            to_delete=[]
            
    if to_delete:
         await ctx.channel.delete_messages(to_delete) ```
#

ended up using that, a bot dev i know made it

sick birch
loud flicker
#

guys i need help, i can surely load the cogs but if its a slash command cog it doesnt show up on the slash commands list:

import discord
from discord.ext import commands
import subprocess
import importlib
import sys
import os

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

    @commands.slash_command(name='reload', guild_ids=[1184567083363745862])
    async def _reload(self, ctx):
        if ctx.author.id == 397747000709349377:
            botMessage = await ctx.respond("Please wait...", ephemeral=True)

            await botMessage.edit_original_response(content=f"Update complete - loading modules...")

            # Reload all loaded cogs
            for filename in os.listdir("./cogs"):
                if filename.endswith(".py"):
                    cog_name = f"cogs.{filename[:-3]}"
                    try:
                        if cog_name not in self.bot.extensions:
                            self.bot.load_extension(cog_name)
                            await botMessage.edit_original_response(content=f"Loaded {cog_name}")
                        else:
                            self.bot.reload_extension(cog_name)
                            await botMessage.edit_original_response(content=f"Reloaded {cog_name}")
                        # self.bot.reload_extension(cog_name)
                        # await botMessage.edit_original_response(content=f"Reloaded {cog_name}")
                    except Exception as e:
                        await ctx.send(f"Failed to reload {cog_name}: {e}")
            
            await self.bot.sync_commands() ##here it gives errors too
            await botMessage.edit_original_response(content=f"Reloading complete.")

def setup(bot):
    bot.add_cog(Reload(bot))
slate swan
#

You sync the commands at some point when starting the bot at least, right?

barren sun
#

can someone take a look at my scripts and help me find out why the .py I'm trying to import into my main script won't be recognized or initialized?

tiny coyote
#
class OPBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix = ".", intents = intents)
    
    async def onready(self):
        await self.wait_until_ready()

        print(f"Bot {bot.user.name} is now online")

    async def setup_hoop(self):
        for name in os.listdir("cogs."):
            if name.endswith(".py"):
                try:
                    await self.load_extension(f"cogs.{name[:-3]}")
                    print(f"The Commands in file cog.{name[:-3]}")
                except Exception as error:
                    print(f"This file cant be loaded Pleas fix this error \n {error}")

bot = OPBot()
#

cogs dont work

#

doesnt recognize the commands

slate swan
#

Cause you misspelled both method names

#

Its on_ready and setup_hook

tiny coyote
#

oh damn

#

sorry

final iron
#

await self.wait_until_ready()

#

?

#

What is the point of this lol

woeful raft
#

Hi , how can I make that everytime there is someone sending a message in a specific channel , my bot sends a messsage like @friend

pale zenith
#

but instead, you can check if message.channel.id == your channel ID: and do stuff inside that if

woeful raft
somber sky
#

nvm i just realized

pale zenith
# woeful raft im completlyt new to coding is there any video that could help me with that code...

The unfortunate reality is that when it comes to discord.py, most videos aren't good. Most show bad practices, and could generally be misleading. And with the fast nature of the discord API, they tend to be out-of-date fairly quickly, so putting effort into making a good one is unfortunately pointless.

The best thing to do is first, try picking up the python basics before doing something complex like a discord bot. After that, the best place to help yourself is the official examples and documentation. (see this channel's topic)

See the main page of the docs. Especially the Getting Started section:
https://discordpy.readthedocs.io/en/latest/index.html

somber sky
#
@client.event
async def on_ready():
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute(
                'CREATE TABLE IF NOT EXISTS users (settransactionschannel STRING, setlogschannel STRING, setalertschannel STRING, setgametimechannel STRING, setpickupschannel STRING, setstreamschannel STRING, setfreeagencychannel STRING, setnoticeschannel STRING, setverdictschannel, guild INTEGER, setdemandchannel STRING)'
            )
        await db.commit()
    async with aiosqlite.connect("main.db2") as db2:
        async with db2.cursor() as cursor:
            await cursor.execute(
                'CREATE TABLE IF NOT EXISTS users (setrefereerole STRING, setcandidaterole STRING, setcaptainrole STRING, setsuspendedrole STRING, setstreamerrole STRING, guild INTEGER, seteligiblerole STRING)'
            )
        await db2.commit()```

```py
 async with aiosqlite.connect("main.db2") as db2:
    async with db2.cursor() as cursor:
        await cursor.execute(
            'SELECT setrefereerole FROM users WHERE guild = ?',
            (ctx.guild.id, ))
        data = await cursor.fetchone()
        if not data:
            pass
        else:
            refrole = ctx.guild.get.role(int(data[0]))```

```py
        if refrole is not None:
          refrole = refrole.mention
        else:
          refrole = "None"```

I set the role and it keeps returning as none it doesnt do this for any of the other ones like setcaptainrole or any of them so im really confused, maybe im not saying something im supposed to idk
loud flicker
nocturne urchin
vale wing
#

Also yeah gonna recommend some code design improvements

#

But to actual issue

vale wing
#

And show how you insert the role

naive briar
vale wing
# somber sky ```py @client.event async def on_ready(): async with aiosqlite.connect("main...

And now to design issues and heck they are major

  1. You DO NOT need 2 databases. No matter the case, you DO NOT need 2 databases. I'm just completely sure about this, either merge two tables' columns together or create a separate table in main database. However if you have some messed up complex databases system that is shared among several projects you can keep it this way
  2. One connection. Do not create connection every time you need to make a query. Instead, subclass your bot
class MyBot(commands.Bot):
    db: aiosqlite.Connection

    async def setup_hook(self):
        self.db = await aiosqlite.connect("main.db")

    async def close(self):
        await self.db.close()
        await super().close()

    async def execute(self, query: str, args: tuple) -> aiosqlite.Cursor:
        # I forgot how it's done in aiosqlite but from what I remember this way, refer to docs or test to be sure
        cur = await self.db.execute(query, args)
        await self.db.commit()
        return cur

bot = MyBot(...)
  1. SQL script. Instead of hardwriting CREATE TABLE into python code, bring them out to a separate .sql file and execute contents of the file on initialization. You can format the file nicely so you don't get confused.

Generally would recommend to look at my old birthday bot. Has some flaws and is not in dpy but good for understanding how to connect and use database in a better way

#

Yeah there's Connection.executescript() method now so you don't need that ugly for loop for file executing, can just pass entire file content

primal wave
#

anyone know how to code or what's the code for a auto delete user msg bot

vale wing
vale wing
primal wave
vale wing
#

Listen to on_message and compare message.author.id to that certain user's ID

vale wing
#

Well I am feeling spoon feeding so I am gonna spoonfeed

primal wave
#

🙏🏼

vale wing
#
import discord


client = discord.Client(intents=discord.Intents(message_content=True, guild_messages=True))

@client.event
async def on_message(message: discord.Message):
    if message.author.id == USER_YOU_WANNA_BULLY_ID:
        await message.delete()

client.run("TOKEN")
#

Very minimal, not even using commands framework 👁️👄👁️

primal wave
#

@vale wing oh snap

ionic pilot
vale wing
#

They can be funny

#

Can be annoying

primal wave
#

fr

primal wave
ionic pilot
#

some funny too

#

but some are just un needed

vale wing
#

And we ain't helping with selfbots here

primal wave
vale wing
#

Yep

primal wave
# vale wing Yep

how do i get it to work with a regular bot so the bot delete the msg

vale wing
#

By replacing corresponding things in that code, setting up environment and running it

#

I ain't wanna spoonfeed that sry

primal wave
#

alrr

#

so the discord bot gonna auto delete the msg @vale wing

vale wing
#

Yes

primal wave
#

alr

#

@vale wing how do i run it do i jus download

vale wing
primal wave
#

alr

latent pier
#

How can i get Error's full traceback from on_command_error(ctx, error)

dreamy dune
vale wing
#
s = traceback.format_exc(error)
latent pier
hazy kraken
#

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited

#

!e RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited

unkempt canyonBOT
#

@hazy kraken :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
003 |                               ^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax
dreamy dune
hazy kraken
#

mm

#

this is the error

dreamy dune
#

Yes you have to await the function call. If you don't know what await is you should probably learn about about async before making bots

hazy kraken
#
import os 
import asyncio
import discord  
from dotenv import load_dotenv
from discord.ext import commands   

# Intents 
intents = discord.Intents.all()  

client = commands.Bot(command_prefix="m.", intents=intents, help_command=None) 
# Load Cogs
async def load_extensions():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await client.load_extension(f'cogs.{filename[:-3]}')
# Load Tokens
load_dotenv()
token = os.getenv('MOMO_TOKEN')

async def main():
    async with client:
        await load_extensions()
        await client.start(token)
asyncio.run(main())
shrewd apex
#
  • why would run a python bot using npm
  • also you sure u have installed the correct discord library discord.py and don't have other forks installed simultaneously?
unkempt canyonBOT
hazy kraken
shrewd apex
#

fair i suppose i have a custom function under my bot class which does that for me when i edit cogs

hazy kraken
shrewd apex
#

I have used a few of them so far ones discord.py and disnake are the ones that stand out for me mostly
disnake has hot reloading with cogs so thats a feature i liked a lot so i ported it over to discord.py

vale wing
hazy kraken
#

i see

shrewd apex
vale wing
#

Instead of python bot.py try venv/Scripts/python.exe bot.py

hazy kraken
#

before worked for me.

vale wing
#

Or bin depending if you're on unix

hazy kraken
#

im in windows

shrewd apex
vale wing
#

Yeah

hazy kraken
vale wing
#

Oh nvm I thought the module was not found

slate swan
vale wing
#

It's an outdated library most definitely

shrewd apex
hazy kraken
vale wing
#

pip freeze

shrewd apex
#

also might wanna pip freeze and remove unwanted packages using pip uninstall

slate swan
#

just run this script ```py
import os
import sys

py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands discord-ext-slash"

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")

hazy kraken
#
PS C:\Users\zhiya\Desktop\BOT de discord\momo-bot> pip list
Package            Version
------------------ ------------
aiohttp            3.8.6
aiosignal          1.3.1
annotated-types    0.6.0
anyio              4.2.0
async-timeout      4.0.3
asyncpg            0.29.0
attrs              23.1.0
certifi            2023.11.17
charset-normalizer 3.3.2
colorama           0.4.6
crash              0.30.1
crate              0.34.0
discord.py         2.3.2
distlib            0.3.8
distro             1.9.0
exceptiongroup     1.2.0
filelock           3.13.1
frozenlist         1.4.1
h11                0.14.0
httpcore           1.0.2
httpx              0.26.0
idna               3.6
multidict          6.0.4
mysql-connector    2.2.9
mysqlclient        2.2.1
nodemon-py-simple  0.0.7
numpy              1.26.3
openai             0.28.1
pandas             2.1.4
pip                23.3.2
pipenv             2023.11.15
platformdirs       4.1.0
prompt-toolkit     3.0.43
py-cord            2.0.0b7
py-mon             2.0.3
pydantic           2.5.3
pydantic_core      2.14.6
pygame             2.5.1
Pygments           2.17.2
pymon              1.1
python-dateutil    2.8.2
python-dotenv      1.0.0
pytz               2023.3.post1
requests           2.31.0
setuptools         69.0.3
six                1.16.0
sniffio            1.3.0
sqlparse           0.4.4
tabulate           0.9.0
toml               0.10.2
tqdm               4.66.1
typing_extensions  4.9.0
tzdata             2023.4
urllib3            2.0.7
virtualenv         20.25.0
watchdog           3.0.0
wcwidth            0.2.12
yarl               1.9.4
PS C:\Users\zhiya\Desktop\BOT de discord\momo-bot>
slate swan
#

py-cord

slate swan
hazy kraken
#

alr

hazy kraken
slate swan
#

Yea

hazy kraken
#

alr

vale wing
hazy kraken
hazy kraken
slate swan
#

Yea i dont understand that language

vale wing
slate swan
#

But just uninstall py-cord

hazy kraken
#

oki

north kiln
#

his python is not in PATH

#

I think

hazy kraken
# slate swan Yea i dont understand that language

(.venv) PS C:\Users\zhiya\Desktop\discord BOT\momo-bot> python script.py
"C:\Users\zhiya\Desktop\BOT" is not recognized as an internal or external command, executable program or batch file.
"C:\Users\zhiya\Desktop\BOT" is not recognized as an internal or external command, executable program or batch file.
(.venv) PS C:\Users\zhiya\Desktop\discord BOT\momo-bot>

north kiln
#

also just listing all the packages name to uninstall looks funny to me

hazy kraken
#

maybe should i have to reinstalling the env?

shrewd apex
#

u can instead do this

venv/Scripts/activate.bat
pip uninstall pycord
#

first like activates the venv in the current terminal and second line uninstalls pycord

shrewd apex
#

wdym u cant?

#

did u make sure u entered exactly what i sent above

hazy kraken
#

yes

#

alr now yes

hazy kraken
shrewd apex
#

u can try running the bot now

hazy kraken
#

alr

slate swan
#

Install python-dotenv

#

!pypi python-dotenv

unkempt canyonBOT
shrewd apex
# hazy kraken
pip install python-dotenv

also make sure venv is enabled before any install process u run in the future same when ur running the bot

hazy kraken
shrewd apex
#

enable it

#

to check if ur venv is on ur CLI will be prefixed like (momo-env)

shrewd apex
#

always active the venv before running any commands

hazy kraken
shrewd apex
#

tbh just use python to directly run the bot node seems painful here

hazy kraken
#

look

hazy kraken
# shrewd apex tbh just use python to directly run the bot node seems painful here

i've
a folder called Cogs
inside of this folder i've 3 sub-folders: Events, prefixCommands, slashCommands
then inside of each folder i've the files of my cogs
i'm trying to doing this

async def load_extensions():
    for folder in os.listdir('./cogs'):
        if os.path.exists(os.path.join('./cogs', folder, )): 
            await client.load_extension(f'cogs.{folder[:-3]}')  
shrewd apex
#

thats not how u load cogs its partially correct ur pointing to the folder containing the cogs u need to point to the individual cogs as files instead

hazy kraken
shrewd apex
#

so u would have to recursively or through some other method get all files in the directory

shrewd apex
#

!d glob.glob

unkempt canyonBOT
#

glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)```
Return a possibly empty list of path names that match *pathname*, which must be a string containing a path specification. *pathname* can be either absolute (like `/usr/src/Python-1.5/Makefile`) or relative (like `../../Tools/*/*.gif`), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.
shrewd apex
#

!d os.walk

unkempt canyonBOT
#

os.walk(top, topdown=True, onerror=None, followlinks=False)```
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory *top* (including *top* itself), it yields a 3-tuple `(dirpath, dirnames, filenames)`.
shrewd apex
#

either method works

hazy kraken
# shrewd apex either method works

should be like this right?

C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py:25: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension(cog_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cogs.Events.events
Loaded cogs.prefixCommands.help
Loaded cogs.prefixCommands.ping
Loaded cogs.prefixCommands.purge
Loaded cogs.prefixCommands.randome
Loaded cogs.slashCommands.Reacciona
shrewd apex
#

await it

hazy kraken
#

this is the code

vale wing
#

Oh yall finally got through this 💀

hazy kraken
hazy kraken
# shrewd apex await it

and the terminal send this error


> bot-main@1.0.0 dev
> nodemon bot.py && cls

[nodemon] 3.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: py,json
[nodemon] starting `python bot.py`
C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py:25: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension(cog_name)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded ./cogs/Events/events.py
Traceback (most recent call last):
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 958, in _resolve_name
    return importlib.util.resolve_name(name, package)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\importlib\util.py", line 32, in resolve_name
    raise ImportError(f'no package specified for {repr(name)} '
ImportError: no package specified for './cogs\\Events\\events.py' (required for relative module names)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 40, in <module>
    asyncio.run(main())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete
    return future.result()
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 38, in main
    await load_extensions()
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\bot.py", line 30, in load_extensions
    await client.load_extension(cog_path)
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 1005, in load_extension
    name = self._resolve_name(name, package)
  File "C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\discord\ext\commands\bot.py", line 960, in _resolve_name
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension './cogs\\Events\\events.py' could not be loaded.
[nodemon] app crashed - waiting for file changes before starting...
vale wing
#

Package name should be like cogs.Events.events, not the filename

slate swan
#

Line 9 for example

#

And not sure what line 14 is supposed to do but yeah

hazy kraken
slate swan
#

And you might want to reset your token now

hazy kraken
hazy kraken
hazy kraken
#

--- idk why .. the dotenv not working anymore

#

ImportError: cannot import name 'load_dotenv' from 'dotenv' (C:\Users\zhiya\Desktop\BOT de discord\momo-bot\momo-env\lib\site-packages\dotenv_init_.py)

vale wing
#

Precisely

hazy kraken
#

is like .. is not reading.. the directory

vale wing
#

Do this

import pathlib

for p in pathlib.Path("cogs").glob("**/*.py"):
    await bot.load_extension(p.as_posix()[:-3].replace("/", ".")(
hazy kraken
#

i sustituit by what?

vale wing
#

That's slicing

hazy kraken
#
async def load_extensions(folder="./cogs"):
    for subdir, _, files in os.walk(folder):
        for file in files:
            if file.endswith(".py"):
                cog_path = os.path.join(subdir, file)
                cog_name = cog_path.replace(os.sep, "/").replace(".py", "")
                try: 
                    await client.load_extension(cog_name)
                    print(f"Loaded {cog_name}")
                except Exception as e:
                    print(f"Failed to load {cog_name}: {e}")
#

by

for file in files:
            if file.endswith(".py"):
                cog_path = os.path.join(subdir, file)
                cog_name = cog_path.replace(os.sep, "/").replace(".py", "")
hazy kraken
hazy kraken
dense coral
#

Hey! I want to make a smart leaderboard that updates every 10 minutes.
But the problem is that my bot is public, and I want to know what is the best way to do it with hundreds of servers.

vale wing
hazy kraken
#

Alr

vale wing
#

In typical database it would look like

SELECT id, score FROM guilds ORDER BY score DESC LIMIT 10```
dense coral
vale wing
#

So you only want the background loop?

dense coral
#

yeah

#

but I have 100 servers

vale wing
#

!d discord.ext.tasks.loop check entire page, there are plenty of examples

unkempt canyonBOT
#

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

what's reconnect do?

vale wing
vale wing
dense coral
hazy kraken
#

finally works tysm

dense coral
# vale wing Everything's in docs

I have done it, but the loop doesn't work
@tasks.loop(seconds=10)
async def smartleaderboard(self):
print("1")
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
guild_db = await cursor.execute("SELECT guild FROM servers")
guild_ids = await guild_db.fetchall()
for guild_id in guild_ids:
.....
it prints "1" but didn't edit the message... can I send u the full code in dms?

#

this is the loop start:

# while on_ready event
if not self.smartleaderboard.is_running():
            
            self.smartleaderboard.start()```
vale wing
#

Do not send me code in dms, instead use pasting service

#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

vale wing
dense coral
vale wing
#

Okay send full code

vale wing
dense coral
hazy kraken
#

I’m having a problem in the interaction on a Selection

dense coral
vale wing
dense coral
#

ty

vale wing
#

Also start the loop in init

dense coral
#

wdym

#

on the class?

vale wing
#

You checked the examples in doc I linked?

#

There's an example for cog which shows precisely what I mean

#

On top of page jic

#

@dense coral could you also send database structure

dense coral
#
class Smartleaderboard(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.smartleaderboard.start()```
you mean like this?
young dagger
#

Is there any way I could add the emojis in an easier way? They must be in the order: top, jungle, mid, adc, support for each team.

role_emojis = [':top:', ':jungle:', ':mid:', ':adc:', ':support:']

embed.add_field(name=":crossed_swords: Custom Team 1",
                value=f"".join(f"\n> {role_emojis[i]} {u['member'].mention}" for i, u in enumerate(team_1)),
                inline=True)

embed.add_field(name=":crossed_swords: Custom Team 2",
                value=f"".join(f"\n> {role_emojis[i]} {u['member'].mention}" for i, u in enumerate(team_2)),
                inline=True)
hazy kraken
#

Not working the commands

dense coral
vale wing
#

No I just need the structure to understand what you are even doing there

#

That thing can be optimized a lot I'm pretty sure

hazy kraken
dense coral
# vale wing No I just need the structure to understand what you are even doing there
"CREATE TABLE IF NOT EXISTS servers (message ID, info TEXT, users TEXT, votes INTEGER, guild ID)" #table to save all servers and their votes (like top.gg), the message is the vote message
"CREATE TABLE IF NOT EXISTS smartleaderboards (channel INTEGER, message INTEGER, guild ID)" # save all the smart leaderboards to update them easy and check if there is already one of each server.

I have this information if it'll help u

vale wing
vale wing
#

Also no PK in both tables

hazy kraken
dense coral
hazy kraken
vale wing
#

Sqlite

hazy kraken
#

Ooh

dense coral
hazy kraken
dense coral
#

oh

#

why do I need a pk? (I am relatively new as sqlite)

hazy kraken
#

Wait maybe can meaning other thing

hazy kraken
#

NOW YES

vale wing
red blade
#

does anyone know why i am getting an invalid token error when i use the correct token?

naive briar
#

Bot or user token? 🤨

pale zenith
#

inb4 it's the client secret

red blade
dense coral
young dagger
#

How can I make two fields next to each other of total 4 fields?

pale zenith
#

like \u200b (note that this looks dogshit on mobile)

#

could also be simply two fields

young dagger
pale zenith
#

i think this is the best option, that would look decent-ish on mobile

young dagger
# pale zenith

Something like this?

    {
      name: "Custom Team 1",
      value: "@Beerhunter (1545)\n\n**Summoner Name**\nThe Beerhunter #EUW",
      inline: true
    },
    {
      name: "Custom Team 2",
      value: "@Sami (1659)\n\n**Summoner Name**\nSami #EUW",
      inline: true
    },
young dagger
#

Mhm intresting, thanks @pale zenith

pale zenith
#

no problem

formal basin
#
2024-01-19 16:55:28 ERROR    discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
#

why is it reconnecting

#

WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.

slate swan
#

self-explainatory

hazy kraken
hazy kraken
#

Will u help me … with the interaction of my command help … when I’m arriving home

hazy kraken
#

That gives an error in the interaction

#

When I select a choice

nocturne urchin
#

hey all!

noob to this server but not new to discord or python. I have a bunch of command line code that interacts with discord via webhooks and request.gets with hard-coded authorization in headers... but am ready to move to a proper bot.

Is there a "bot getting started" guide here?

so glad to have found this! Thanks in advance?

slate swan
#

Channel description

#

And pinned messages also have some helping resources

vale wing
slate swan
#

.topic

lament depotBOT
#
**What commands/features are you proud of making?**

Suggest more topics here!

vale wing
pale zenith
slate swan
pale zenith
#

I still have some stuff missing

#

ive just been lazy blobsleeping

sick birch
sullen chasm
#

@client.tree.command(name="add_dev", description="Gives Dev Roles")
async def count_interaction(interaction: discord.Member):
Member.add_roles(id="1197257756038680696")
await interaction.response.send_message("Given Role!")

its not working

vale wing
#

This is so wrong the only thing I can do is spoonfeed 😭

#

Why is interaction typehinted as discord.Member 😭

sick birch
sullen chasm
#

im not sure im new

vale wing
#

Why do you call object-unbound Member.add_roles 😭

#

And it doesn't even have id kwarg 😭

vale wing
sullen chasm
#

give a player a role

vale wing
#

Is this command that displays in "apps" when you right click user/message

#

Or just slash

sullen chasm
#

im trying to make it do /add_role [username]

sick birch
# sullen chasm im trying to make it do /add_role [username]

Okay. The format for slash command callback parameters is the first argument is always going to be interaction: discord.Interaction (unless it's inside a class, in which it'll have self like usual) - then followed by each slash command argument and it's type. In your case, since you want to accept a user, you'll be accepting a discord.Member:

async def add_role(interaction: discord.Interaction, member: discord.Member):
  ...
vapid parcel
#

In what senario would this occur? Where a bot can NOT add reactions to a users message?

#

Because im thinking the bot can't add reactions because the user has it blocked? But I don't know if that can mess with it..?

hushed galleon
formal basin
#
2024-01-19 16:55:28 ERROR    discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

why is it reconnecting

WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.

young dagger
pale zenith
#

perhaps make the top part more compact somehow

young dagger
pale zenith
#

is that "Queue Popped!" message important? if it isn't it could be removed

#

@young dagger Thonk

young dagger
pale zenith
#

the problem is the field issue

#

i can't think of anything better lmao

vapid parcel
#

Like the coding part, I got the dev portal part.

hushed galleon
vapid parcel
#

I am confused asf GoofySkull

hushed galleon
#

confused about what?

vapid parcel
#

wanting to know how to make a command be premium, and if discord has a way to check if the user is premium..?

#

Thats what im talking abt.

hushed galleon
#

if you have the development version installed from the discord.py repo, i assume you can check Interaction.entitlements to see if they paid for a particular Stock-Keeping Unit, and if not you can use interaction.response.require_premium() to tell them that it's premium

#

weird that the commit didnt include an app_commands.check for convenience

vapid parcel
#

So there is a development version? So I have to have that development version of discord.py to use Premium related things?

hushed galleon
#

"development version" really means installing directly from the git repository

#

for example pip install git+https://github.com/Rapptz/discord.py for the latest commit, or for installing a specific commit, pip install git+https://github.com/Rapptz/discord.py@cb3ea9b889dcdefa5aa81b1dc7ce4e3e87abeeb0

vapid parcel
#

So I would need the development version tho right?

hushed galleon
vapid parcel
#

So I should just do pip install git+https://github.com/Rapptz/discord.py@cb3ea9b889dcdefa5aa81b1dc7ce4e3e87abeeb0? Then look at docs on how to do it?

hushed galleon
#

yes, and specifically latest docs

vapid parcel
#

So, it does have an auto check correct?

hushed galleon
#

thats why i was wondering why there wasn't an app_commands.check to make it a bit easier

vapid parcel
#

Is there any examples?

hushed galleon
#

doesnt look like it

vapid parcel
#

hm...

hushed galleon
#

huh, api docs you're only allowed to publish one SKU, so i guess thats why they dont allow specifying a particular SKU with require_premium()

#

well regardless, just based on their documentation i assume you'd use it like: ```py
@tree.command()
async def my_command(interaction):
has_premium = False
for entitlement in interaction.entitlements:
if entitlement.sku_id == 1234:
has_premium = True

if not has_premium:
    return await interaction.response.require_premium()``` `discord.utils.get()` would make it a bit simpler too
vapid parcel
#

This is lowkey annoying too cuz you have to have a verified bot to test this stuff on n stuff

hushed galleon
#

curiously there's Interaction.entitlement_sku_ids but it checks for entitlement_skus in the interaction payload which isn't documented on the discord API

vapid parcel
#

which is like more down time ya know lol

slate swan
#

is it hard to integrate chatgpt into a discord bot?

naive briar
#

No

vapid parcel
#

depending on what you are doing, its really simple.

tall creek
#
An error occurred while extracting information: An error occurred while extracting information: ERROR: Unable to extract uploader id
rugged shadow
spark nimbus
#

so back to my wordle command as i have some free time so i get into it and i wanted to change the footer when someone got the answer or lost so i have added this code to my function that changes the embed:```py
def update_embed(embed: discord.Embed, guess: str) -> discord.Embed:
puzzle_id = int(embed.footer.text.split()[16])
answer = popular_words[puzzle_id]
colored_word = generate_color_word(guess, answer)
empty_slot = generate_blanks()
embed.description = embed.description.replace(empty_slot, colored_word, 1)

try:
    if guess == answer:
        num_empty_slots = embed.description.count(empty_slot)
        if num_empty_slots == 0:
            embed.footer(text="\n\nPhew!")
        if num_empty_slots == 1:
            embed.footer(text="\n\nGreat!")
        if num_empty_slots == 2:
            embed.footer(text="\n\nSplendid!")
        if num_empty_slots == 3:
            embed.footer(text= "\n\nImpressive!")
        if num_empty_slots == 4:
            embed.footer(text="\n\nMagnificent!")
        if num_empty_slots == 5:
            embed.footer(text= "\n\nGenius!")
        elif num_empty_slots == 0:
            embed.footer(text=f"\n\nThe answer was {answer}!")
    return embed
except Exception as e:
    print(e)
    traceback.print_exc()```

at the start i got no error so i added the traceback and still no error...
i dont really know what to do..

slate swan
#

im going to take a hard pass on that then

tall creek
#
An error occurred while extracting information: An error occurred while extracting information: ERROR: Unable to extract uploader id
formal basin
#
2024-01-19 16:55:28 ERROR    discord.client Attempting a reconnect in 1.62s
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 659, in connect
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.9/site-packages/discord/gateway.py", line 646, in poll_event
    raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000

why is it reconnecting

WARNING discord.gateway Can't keep up, shard ID None websocket is 24.5s behind.

fading yew
vale wing
# fading yew question regarding database schema and storing variables of unfixed data type, i...

You mentioned that "an event can be practically anything" which is totally wrong. The events your bot can handle are limited and you are to define them.

Regarding unfixed amount of keys there are several solutions

  1. Just switch to json-like db like mongo
  2. Use JSON data type (from what I saw your engine supports that). If it doesn't, you can always store it as plain text lol
  3. Create some table with guild, key, type and value columns. Essentially any data can be interpreted as text and all you have to do is convert it based on type.

I strongly feel like you have xy problem rn and the desired result can be reached in another way

fading yew
# vale wing You mentioned that "an event can be practically anything" which is totally wrong...

An event can be practically anything tho (yeah, ik I'd need to write the code for it).. I could make it so that, on the click of a button, my garage door opened/closed (I don't actually have a garage, just saying).

  1. Is pretty much what I did, yeah. 1 and 3 are other options which I've considered, as listed in my comment. Question is, what's "better"?

Could be xy, but in what other way could I reach this result? That's the question

vale wing
#

What feature are you trying to implement

fading yew
fading yew
# vale wing What feature are you trying to implement

That's the thing, the list of features isn't fully defined yet and will be expanding. I was explicitly told that the bot needs to be able to store user and guild variables, as I described in the post, so that's what I'm trying to do, and make it work with "events", where I will be adding the code for new events as needed, so that others could then branch-chain "events" together to create a possible sequence of actions (they'll be doing this through a gui of sorts)

vale wing
restive mantle
#

How come this doesnt work, the error I keep getting is: ImportError: cannot import name 'Intents' from 'discord' (unknown location)

import os

import discord
from discord import Intents
from discord.ext import commands

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

# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!', intents=intents)

# Event: Bot is ready
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

# Command: Ping
@bot.command(name='ping')
async def ping(ctx):
    await ctx.send('Pong!')

# Run the bot with the token
bot.run("")
vale wing
#

If that's what I think about, you can just make sort of custom commands language and parse it

vale wing
restive mantle
vale wing
#

Did you install it in venv

restive mantle
vale wing
#

Yeah no venv then

#

!venv

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
restive mantle
#

So I should install this instead?

fading yew
# vale wing Do you mean like custom commands

They don't create custom commands, but they do need to be able to chain pre-created custom commands, which I will be adding as necessary, which will be using user/guild variables

vale wing
#

You only need the note and how to create venv. To activate it, ctrl + shift + p -> Python: Select Interpreter and select the venv inside your current project. After that, make sure to create new terminal and do pip install discord.py @restive mantle

vale wing
fading yew
restive mantle
vale wing
#

Might be a bad design of language but it's up to you how to do that

#

Just don't use exec when parsing ☺️

vale wing
#

Also install python from official python site, ms store version is broken af

vale wing
#

Data storage comes to just a bunch of text

#

@fading yew

fading yew
vale wing
#

It gives you the extensibility

restive mantle
#

Thanks for the help also🤍

vale wing
#

And how can you do something without python code?

restive mantle
#

oh god

#

🧍‍♂️

vale wing
#

🗣️

#

Delete the inner one and open parent directory

fading yew
# vale wing And how can you do something without python code?

Who would be using this custom language again? 😅 I was thinking I'd do smth more like: a searchable drop-down menu with possible pre-defined "actions/events/commands", when chosen, additional options may appear, and the ability to chain this to another one. But this is about the gui. I'm just thinking about how to store the stuff. I wouldn't be storing the python code, that would just be.. well, part of the bot. The events table would hold the unique name of one of these "actions" from which one can choose from a drop-down, which would be the key in a python dictionary, containing the function to be executed with the other stored parameters from the events table, pulling variables if needed from the value table. After creating such a chain of events, it would be executed.
How does this custom language help me store stuff? I don't get it pithink

restive mantle
#

but now everything is restored ☺️

vale wing
vale wing
restive mantle
late cypress
#

how can i get user id from username

vale wing
restive mantle
#

It's kinda weird tho, because I watched some yt tutorials. And they don't use venv and still get it to work.

vale wing
#

Seems alright. Create python scripts in root dir, not in venv

restive mantle
vale wing
#

Now do ctrl + shift + p -> Python: Select Interpreter

restive mantle
#

ok

vale wing
#

Can also collapse the venv since you don't need its contents

restive mantle
#

So like this then?

vale wing
# restive mantle I see

It is possible ofc, but just install both discord.py and pycord globally and not a single project will run. Venvs are for isolating dependencies

vale wing
restive mantle
#

You don't use visual studio?

vale wing
#

I have it, but my open scripts display as tabs

restive mantle
#

Now lets see if the code works

vale wing
#

Great, now open new terminal and install dpy

#

Make sure there's (venv) at the beginning of prompt

restive mantle
#

Should I uptade?

vale wing
#

You can but that's optional

restive mantle
#

Alrighty, now when that's done

#

Lets see if the code works

late cypress
#
member = await guild.fetch_member(username='msii9')
return member.id

how can i get user id from username because fetch_member only takes id

vale wing
restive mantle
#

@vale wing It's working now man!! Thanks for the massive help. 🫶

late cypress
#
member = await guild.get_member_named('msii9').id
return member   ```
vale wing
#

First, it's not a coroutine hence you don't need to await it

#

Second, is members intent on

late cypress
#

ah

#

it worked

vale wing
#

👍

slate swan
#

ban the spoon feeders

#

!

drifting arrow
#

What's the object type called if someone tags a channel?

#

I have a command that's meant to take a channel ID, I never in my life expected someone to just @ a channel lol

vale wing
slate swan
unkempt canyonBOT
#

class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.

The following implement this ABC...
slate swan
#

thats every channel

#

but you can only accept for example text channels only

#

then its

#

!d discord.TextChannel

unkempt canyonBOT
#

class discord.TextChannel```
Represents a Discord guild text channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
drifting arrow
#

so do I just do "If type(input) == "TextChannel" i'll detect if someone has @'d a channel instead of using a channel ID?

slate swan
#

you can use built in converters

#

instead of checking for correct type manually

restive mantle
#

How can I create these boxes? Instaed of the bot sending just a normal message?

#

Or what's the name of these boxes

naive briar
#

Those are called embeds

restive mantle
#

ooo thanks

slate swan
#

more about it here smileh

restive mantle
#

👍

drifting arrow
#

Ty @slate swan 😄

#

This change is much better

#

now I dont have to rely on people doing the command right.

slate swan
drifting arrow
#

While im here. How do I make a command sleep for a second?

#

Someone mentioned it once before

#

like many days ago

slate swan
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
spark nimbus
#

well i have my bot bot with not many commands and i thought to create more commands but i need ideas if you have something that can be challenging and fun after pls reply

vale wing
spark nimbus
#

what are the functions?

vale wing
#

Sorry it was a local meme

spark nimbus
#

ok

vale wing
#

Tbh I already spent all my ideas on bobux bot so can't really help

spark nimbus
#

ok

mighty pilot
#

how could i get an emoji object out of message content

#

end goal is to get the link for the emoji someone sends

naive briar
#

With re or something similar

mighty pilot
#

gross, regex

#

alright, thanks. wasnt sure if there was an easier way i wasnt aware of

spark nimbus
slate swan
#

anyone know a good low cost db that i can use for my bot?

mighty pilot
honest falcon
#
@bot.event
async def on_message(message):
    if message.mentions:
        for member in message.mentions:
            if member.status == discord.Status.offline:
                await message.channel.send(f'{member.name} is currently offline.')
            break

i tried to code a bot that when someone being mentioned but offline, the bot gonna notify that they are offline, but when i test the bot, anyone i mention, both online and offline, triggered the bot, anyway to fix this?

mighty pilot
#

anyone have a problem with hybrid commands only working via slash command and not working via text command?

#

you can do hybrid commands and slash commands on one bot, correct?

naive briar
#

Yes

mighty pilot
#

yea everything slash is working but its not triggering if i use the prefix

#

which is the opposite of what i thought would happen when changing this from prefix only command to hybrid

naive briar
#

Are you sure you have the right intents?

mighty pilot
#

all intents

naive briar
#

Processing commands?

mighty pilot
#

wym

naive briar
#

Are you overriding the on_message event? If so, you'd need to call the process command method

#

I have no more idea after this 🫠

mighty pilot
#

i have an on_message event in a seperate cog

naive briar
#

Maybe check your bot's permissions to view the channel that you're running the command?

mighty pilot
#

this bot has basically admin permissions

mighty pilot
#

the hybrid command works flawlessly on one bot, but only the slash command works on the other bot. same cog for both. both have all intents. both bots have the same permissions. HOW

#

oh theres an on_message in the main file.. thats gotta be it

slate swan
#

So... how do embed videos work? looking at the docs and saw that was added. do I just input parameters of the url, height and width and it'll implement it into the embed?

#

or is it something I can't set and just use image/thumbnail for that data?

restive mantle
honest falcon
#
@bot.event
async def on_message(message):
    if message.mentions:
        for member in message.mentions:
            if member.status == discord.Status.offline:
                await message.channel.send(f'{member.name} is currently offline.')
            break

i tried to code a bot that when someone being mentioned but offline, the bot gonna notify that they are offline, but when i test the bot, anyone i mention, both online and offline, triggered the bot, anyway to fix this?

late cypress
#
class MyBot(commands.Bot):
     async def on_member_join(self, member):
        role = discord.utils.get(member.guild.roles, id=role_id)
        await member.add_roles(role)    

this on_member_join isnt asigning role on member join whats wront with it

vapid parcel
#

    @commands.Cog.listener()
    async def on_message_delete(self, message):
        log_channel_id = await get_deleted_messages(server_id=message.guild.id, db_connection=self.bot.db_connection)

        if log_channel_id:
            log_channel = self.bot.get_channel(log_channel_id)

            if message.content:
                log_embed = discord.Embed(
                    title="Message Deleted",
                    description=f"Message in {message.channel.mention} deleted.",
                    timestamp=discord.utils.utcnow(),
                    color=config.main_color
                )
                log_embed.add_field(name="Content", value=f"``{message.content}``", inline=False)

                log_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
                log_embed.set_author(name=message.author.display_name, icon_url=message.author.avatar)
                log_embed.set_thumbnail(url=message.author.avatar)

                await log_channel.send(embed=log_embed)```


How could I make this ignore bulk deletions? basically purges. Because if another bot purges, its gonna want to log all of those, it would probably spam the hell out of my bot too
vapid parcel
#

Or how I can do a special embed for Bulk messages/purged messages.

tiny coyote
#

how to get user icon

drifting arrow
#

;-; it annoys me this isnt a thing

naive briar
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).
naive briar
vapid parcel
#

Thanks, but someone just helped me

naive briar
#

Nice

#

I didn't even realize that event existed

vapid parcel
#

I didnt either

drifting arrow
#

\o/

vapid parcel
#

thats why I was shocked lol

tiny coyote
#

is using dict effective in discord coding.?

golden portal
#

that doesn't have anything to do with discord, but dictionaries are pretty good with data lookup speed, it's good for any program you're writing on given a need for it

tiny coyote
#
@bot.event
async def on_message(message):
    async with aiosqlite.connect("Opdb.db") as db:
        async with db.cursor() as c:
            # COLLECTING DATA
            await c.execute("SELECT * FROM status WHERE id = ? ", (message.author.id,))
            
            ID = await c.fetchone()

            await c.execute("SELECT * FROM enemy WHERE id = ?", (message.author.id,))

            enemy = await c.fetchone()

            await c.execute("SELECT * FROM points WHERE id = ?", (message.author.id,))

            p = await c.fetchone()

            # CHECKING IF DATA EXISTS AND IF NOT CREATING DATA
            if not ID:
                await c.execute("INSERT INTO status (id, Name, Level, Fruit, hp, health, damage, xp, xpr, levelr, style) VALUES (?,?,?,?,?,?,?,?,?,?,?)", (message.author.id, "NULL", 0, "None", 10, 10, 1, 0, 5, 15, "Fist"))

            if not enemy:
                await c.execute("INSERT INTO enemy (id, en, eh, ehr, es, el) VALUES(?,?,?,?,?,?)",(message.author.id, 'Snake', 5, 5, 0.5, 0))
            
            if not p:
                await c.execute("INSERT INTO points (id, p, hp, dmg) VALUES(?,?,?,?)",(message.author.id, 3, 1, 1))
            
            # FINISH COLLECTING OR CREATING DATA
        
            
    

                
            
        await db.commit()
    await bot.process_commands(message)

No error received, doesn't do anything tho not sure why

prisma mica
#

hey guys I'm working on my first discord bot and it says it's online and it says it's connected and stuff but it wont reply when I do my command, here's my code (removing the token):


#TOKEN: token

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix=';', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')
    
    # Get the channel where you want the bot to send a message
    channel_id = 1198210346314387456  # Replace with the actual channel ID
    channel = bot.get_channel(channel_id)
    
    # Check if the channel is valid
    if channel:
        await channel.send('Hello, I am your bot! I am now online.')
    else:
        print(f"Error: Channel with ID {channel_id} not found.")

@bot.command(name='hello')
async def hello(ctx):
    global channel
    print("Command Received")
    await channel.send('Hello, I am your bot!')

bot.run('token')
prisma mica
#

also I've discovered that it can't read messages for some reason

subtle jungle
#

I've used the simple script provided my all tutorials to try and host a discord bot, but why can't i get the link to the created web server? it was working fine two months ago, so idk why it suddenly only shows the server as "/"

prisma mica
#

I fixed my problem

vapid parcel
#

How to get invites n stuff like that, on member join. So when someone joins, we wanna know Invite link, and Invite Link Creator, how can we do that?

#
    @commands.Cog.listener()
    async def on_member_join(self, member):
        log_channel_id = await get_member_joins(server_id=member.guild.id, db_connection=self.bot.db_connection)

        if log_channel_id:
            log_channel = self.bot.get_channel(log_channel_id)

            if log_channel:

                log_embed = discord.Embed(
                    title="Member Joined",
                    description=f"{member.mention} has joined the server.",
                    timestamp=discord.utils.utcnow(),
                    color=config.main_color
                )

                log_embed.add_field(name="User ID", value=member.id, inline=False)
                log_embed.add_field(name="Account Created",
                                    value=f"{discord.utils.format_dt(member.created_at, style='R')} / {discord.utils.format_dt(member.created_at, style='f')}",
                                    inline=False)
                log_embed.add_field(name="Server Joined",
                                    value=f"{discord.utils.format_dt(member.joined_at, style='R')} / {discord.utils.format_dt(member.joined_at, style='f')}",
                                    inline=False)

                await log_channel.send(embed=log_embed)
sturdy fractal
#

or link whatever

vapid parcel
#

Yeah ^

spark nimbus
#

Is there a way to send emails with the bot with some other library?

naive briar
#

!d email

unkempt canyonBOT
#

Source code: Lib/email/__init__.py

The email package is a library for managing email messages. It is specifically not designed to do any sending of email messages to SMTP (RFC 2821), NNTP, or other servers; those are functions of modules such as smtplib and nntplib. The email package attempts to be as RFC-compliant as possible, supporting RFC 5322 and RFC 6532, as well as such MIME-related RFCs as RFC 2045, RFC 2046, RFC 2047, RFC 2183, and RFC 2231.

The overall structure of the email package can be divided into three major components, plus a fourth component that controls the behavior of the other components.

spark nimbus
slate swan
#

Have you even tried debugging it on your own

#

e.g. adding print statements to understand the actual flow of your code and where it goes/doesn't go - and what the results of the queries are

#

Because just sending "..." after like 7 hours or something of not doing anything, not even trying, is pretty much useless

tiny coyote
#

been working on this all night

#

But why does message.author.id return a different value from ctx.author.id. Ive been searching for answers but i dont get anything

solar cloak
#

Is there a channel to help people with a code file for a discord bot?

solar cloak
#

Oh cool, thank you.

slate swan
#

!d discord.Message.author

unkempt canyonBOT