#discord-bots

1 messages ยท Page 263 of 1

unkempt canyonBOT
#
Pasting large amounts of code

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

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

left dew
#

why ddint this work? <t:{int(member.created_at.timestamp())}:f*>

slate swan
#

Because you need to read

#

* has a space between f and * and is a mention at the bottom saying

*default

#

Never seen something like that in books, texts, websites, etc.?

left dew
#

ohhhh

slate swan
#

It means it's default, so you don't need to specify anything if you want that format

left dew
#

ohh alright

slate swan
#

Just put <t:timestamp>

left dew
#

ok

slate swan
#

Or if you want, it's <t:timestamp:f> but it's sort of pointless

hasty pike
#

@slate swan if True and True: works same as if True: right?

slate swan
#

True && True = True

hasty pike
#

Both values are true only then if condition will execute?

slate swan
#

If both are true it'll go in the condition

#

If any is false, it won't

hasty pike
#

Yep that's what i want

#

Thanks

formal basin
hasty pike
#

Where can i find discord api integration guide for python?

slate swan
#

There's none

#

Then you use your own knowledge to make an API wrapper around that

#

Making HTTP requests, connecting to the gateway with WebSocket, implementing a rate limiter, etc.

thin raft
#

the f or % doesn't matter

#

you left a ) @hasty pike

hasty pike
#

Ryt

tribal sleet
#

hello bros and female bros

#

I am noob trying to make bot but kick command doesn't work

slate swan
#

Unfortunate

hasty pike
tribal sleet
#

but still doesnt work

hasty pike
#

Show code

tribal sleet
#

from head to foot?

hasty pike
#

Command only

opaque rose
#

Who knows what to do if the discord bot does not respond to commands?

tribal sleet
tribal sleet
#

understandable

opaque rose
#

import discord
from discord.ext import tasks, commands
import asyncio
import random

TOKEN = '' # Replace with your token
YOUR_CHANNEL_ID = 1115912777706508369 # Replace with your channel ID

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

balances = {}

@bot.event
async def on_ready():
print(f'Bot successfully logged in as {bot.user.name}')
await send_message()
send_message_every_3_days.start()

@tasks.loop(hours=72)
async def send_message_every_3_days():
await send_message()

async def send_message():
channel = bot.get_channel(YOUR_CHANNEL_ID)

if channel:
    a = random.randint(1, 500)
    await channel.send(f"Today's ChessCoin exchange rate is: {a}")
else:
    print("Failed to find the specified channel.")

@bot.command()
async def balance(ctx):
user_id = ctx.author.id
if user_id not in balances:
balances[user_id] = 100
balance_amount = balances[user_id]
await ctx.send(f"Your balance is: {balance_amount}")

@bot.command()
async def buy(ctx, amount: int):
user_id = ctx.author.id
if user_id not in balances:
balances[user_id] = 100
balance_amount = balances[user_id]
if amount > balance_amount:
await ctx.send("Insufficient balance.")
else:
balances[user_id] -= amount
await ctx.send(f"You have successfully bought {amount} ChessCoins.")

@bot.command()
async def sell(ctx, amount: int):
user_id = ctx.author.id
if user_id not in balances:
balances[user_id] = 100
balance_amount = balances[user_id]
balances[user_id] += amount
await ctx.send(f"You have successfully sold {amount} ChessCoins.")

bot.run(TOKEN)

thin raft
unkempt canyonBOT
#
Pasting large amounts of code

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

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

hasty pike
slate swan
naive briar
#

So the bot can't read messages

#

!d discord.Intents.message_content - enable this intent

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

opaque rose
tribal sleet
tribal sleet
slate swan
#

To receive messages content you need to enable the message_content intent

#

Similarly to

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
#

Cool

opaque rose
#

that doesn't work either

slate swan
#

"Doesn't work" is very helpful

sharp whale
#

how do we give a specific role to the user by the bot

hasty pike
sharp whale
#

how do i fetch roles

naive briar
#

Ask the docs

#

Great

#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles```
Returns a sequence of the guildโ€™s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.
slate swan
#

It's funny because you can fetch_roles but not fetch_role

#

But get_role and not get_roles

sharp whale
#

hmm

naive briar
#

!d discord.Guild.fetch_roles

unkempt canyonBOT
#

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

Retrieves all [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the guild has.

Note

This method is an API call. For general usage, consider [`roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.roles "discord.Guild.roles") instead.

New in version 1.3.
slate swan
#

That's mainly because Discord doesn't have an endpoint for getting a role by its ID

#

Though they could make it an internal thing idk

#

Fetch all and filter directly

naive briar
#

Me when OOP

slate swan
#

The amount of people that never even heard of that yet they make a Discord but

sharp whale
#

ok

grand moss
#

a quick question:
is there a difference between

@bot.command

and

@bot.tree.command
```?
naive briar
#

What is tree.python

slate swan
#

.python is not a thing

grand moss
#

typo

sharp whale
#

its bot.tree.command

slate swan
#

One is a slash command

#

One is a prefix command

sharp whale
#

@bot.tree.command is slash command

#

and the other one is prefix command

grand moss
#

thanks

slate swan
#

Slash commands are sort of the modern way of doing commands

#

And for prefix commands you need the message content intent, which once a bot is verified it may not have access to it

grand moss
#

would this do anything? I forgot why I put there

@bot.command()
async def hi(ctx):
    await ctx.channel.send("Hello Chat!")
slate swan
#

Unless you have as prefix the bot's mention

grand moss
#

oh ok

#

this one is incomplete then

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

naive briar
slate swan
#

To prevent bots from reading anyone's messages I guess

#

Though now you can soon add bots in DMs and GDMs

#

So bots can read everything there LULW

grand moss
#

oh nice group dms too?

slate swan
#

That's what GDMs are, yep

slate swan
#

You can't get a guild role object by ID

#

There's no such endpoint, you get all roles and filter

thin raft
#

kinda weird tbh

slate swan
slate swan
#

in GDMs

#

have a bot

#

Not everyone iirc

#

Maybe they changed that

#

you can but there is a trick

#

you cant add bot directly to gdm

#

the bot has to create gdm and add you

#

Yeah well that's not what I call supporting adding bots in GDMs

#

well then

#

that on the other side is what I call supporting adding bots in GDMs

#

didnt know they plan that

thin raft
#

!d discord.Client.create_guild

unkempt canyonBOT
#

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

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.

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

!d discord.Client.create_dm ?

unkempt canyonBOT
#

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

Creates a [`DMChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.DMChannel "discord.DMChannel") with this user.

This should be rarely called, as this is done transparently for most people.

New in version 2.0.
slate swan
#

Pretty sure it can't

#

A bot can add users to group channels, but the bot won't be in it I guess

#

Something to test I guess but too lazy to setup a whole OAuth thing

thin raft
#

do users and bots use the same rest api?

slate swan
#

They do

#

Just some endpoints are locked for bots, etc.

#

Just need to pass access tokens of the users

#

But then I don't think the bot will be in the GDM as well, maybe though

thin raft
slate swan
#

Yeah, that's why it's something to test ig

thin raft
#

ill test it later

slate swan
#

Bots don't even get the MESSAGE_CREATE event from GDMs either way

#

So having a bot in GDMs is pretty much pointless

thin raft
#

imagine a gdm with 10 bots

slate swan
#

Not possible

thin raft
#

I just realised why

slate swan
#

Bots can't be authorized with oauth2

grand moss
#

i tried typing hi with and without prefix but didn't work
edit: I figured it out
Edit: no I didn't

slate swan
#

It's with prefix

slate swan
#

!d discord.discord.ext.commands.Author

unkempt canyonBOT
#

discord.ext.commands.Author```
A default [`Parameter`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Parameter "discord.ext.commands.Parameter") which returns the [`author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") for this context.

New in version 2.0.
slate swan
#

And you just need await ctx.send("a")

grand moss
#

this is the part I wrote

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True
#bot = discord.Client(intents=intents)

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

@bot.command()
async def hi(ctx):
    await ctx.send("Hello Chat!")
slate swan
#

I do hope you start the bot at the bottom, right?

grand moss
#

umm sorry?

#

should I paste the whole test code here?

slate swan
#

You have something like

bot.run("...")

where ... is your bot's token

#

PS: Don't ever share that bot token

grand moss
#

I have it at the bottom

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
#

Share everything besides the token, also if you have errors in console it would help

grand moss
#

I dont

slate swan
#

Remove the on_message thing at the bottom

#

Both of the events

#

You don't need them as commands are the way to do that

grand moss
#

ok

#

i removed and got this

thin raft
grand moss
#

I learned it back at school so I thought I could still do this

swift edge
#

code

swift edge
#

bro just paste it

#

here

#

copy and paste

grand moss
#
import discord
#from discord import app_commands
from discord.ext import commands
import os
import requests
import json

print("Hello World")

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True

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

@bot.event
async def on_ready():
  #for syncing commands (supposedly)
  print("Bot is up")
  print(f'Bot is ready. Connected as {bot.user.name}')
  print("Logged in as {0.user}".format(bot))
  try:
    synced = await bot.tree.sync()
    print(f"synced {len(synced)} command(s)")
  except Exception as e:
    print(e)

# CREATES A COUNTER TO KEEP TRACK OF HOW MANY GUILDS / SERVERS THE BOT IS CONNECTED TO.
  guild_count = 0

  # LOOPS THROUGH ALL THE GUILD / SERVERS THAT THE BOT IS ASSOCIATED WITH.
  for guild in bot.guilds:
    # PRINT THE SERVER'S ID AND NAME.
    print(f"- ID: {guild.id} (Name: {guild.name})")

    # INCREMENTS THE GUILD COUNTER.
    guild_count = guild_count + 1

# PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
  print("SampleDiscordBot is in " + str(guild_count) + " guilds.")


#Slash Command Test
@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
  await interaction.response.send_message(
    f"Hi {interaction.user.mention}! This is a slash command")

@bot.command()
async def hi(ctx):
    await ctx.send("Hello Chat!")

@bot.event
async def on_message(message):
  if message.content == "$ping":
     #latency = bot.latency
    await message.channel.send(f"Pong!\nLatency: {latency * 1000}ms")
    
# EVENT LISTENER FOR WHEN A NEW MESSAGE IS SENT TO A CHANNEL.
@bot.event
async def on_message(message):
  # CHECKS IF THE MESSAGE THAT WAS SENT IS EQUAL TO "HELLO".
  if message.content == "$hello":
    # SENDS BACK A MESSAGE TO THE CHANNEL.
    await message.channel.send("Hey Dirtbag :D")

bot.run(os.getenv("TOKEN"))
#

had to remove some because it went over the limit

swift edge
#

all this is not necessary

grand moss
#

if its about the imports I was going to do other stuffs but the prefix command thing kept bothering me

slate swan
slate swan
swift edge
#

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="$", help_command =None, intents=discord.Intents.all())

@bot.event
async def on_ready()
print(f"Ready! Logged in as {bot.user.name}.")

@bot.commands()
async def ping(ctx):
await ctx.send("pong")

bot.run("your token")

slate swan
#

And to get the guild count just to len(bot.guilds) instead of some loop

slate swan
swift edge
slate swan
#

You're also removing their slash command, shit as well

grand moss
#

ok did

slate swan
#

You're removing their custom on_ready content, shit as well

swift edge
#

Ive put "/" before and it didnt pop up the little thingy with the bots commands with a diff category

swift edge
slate swan
#

No

swift edge
#

yes?

slate swan
#

The slash command is gone, it doesn't print what they want

naive briar
slate swan
#

Doesn't sync the slash command either

grand moss
swift edge
slate swan
#

Has all intents enabled which is garbage

slate swan
swift edge
#

wait lemme see the code

slate swan
#

So instead of writing everything new with some nonsense as well, suggest what needs to be fixed instead

naive briar
slate swan
#

Forgot around commands

naive briar
#

Oh, and the bot.commands as well

swift edge
grand moss
#

this is fine?

intents = discord.Intents.default()
intents.typing = False
intents.message_content = True
bot = commands.Bot(command_prefix="$", intents=intents)

nothing worth changing?

#

it works! Thanks!

dusk knoll
#

Did discord.py project get un-abondoned by its maintainer?

slate swan
#

Been over a year, yes

thin raft
#

you should see what's wrong

naive briar
#

Apparently, they didn't

slate swan
#

how is the typing.Optional interpreted by the library and how to convert it to Python 3.10 code?

    @bot.command()
    async def roll(ctx, sides: typing.Optional[int] = 6):
        result = random.randint(1, sides)
        await ctx.send(f"You rolled a {result}!")

lets take this code as example

hasty pike
#
    @commands.Cog.listener()
    async def on_member_ban(self, guild: discord.Guild, user: discord.User) -> None:
        try:
          async for entry in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes=2), action=discord.AuditLogAction.ban):
            await self.client.wait_until_ready()
            user = entry.user.id
            api = random.randint(9, 10)
            victim = guild.get_member(user)
            if v2(guild) and w2(guild, user):
              if pv(guild.id) == 1:
                async with session.put(f"https://discord.com/api/v{api}/guilds/%s/bans/%s" % (guild.id, user)) as r:
                  await guild.unban(user=user, reason=reason)
                  if r.status in (200, 201, 204):        
                    logging.info(f"Successfully banned {user}")
#

@slate swan This isn't working

slate swan
visual island
hasty pike
slate swan
#

both works so you will randomly choose which one to use

hasty pike
#
  1. I don't have answer
slate swan
#

sounds reasonable not gonna lie

hasty pike
hushed galleon
# slate swan how is the `typing.Optional` interpreted by the library and how to convert it to...

interpreted by the library as in how it's used? its more helpful if you have an optional parameter at the start/middle rather than at the end
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#typing-optional
(if you do use it for the last parameter, the only tangible difference is ignoring parsing errors)
in the case of 3.10, int | None becomes Optional[int] so nothing's really different

hasty pike
#

@slate swan#0#0 It isn't working and neither logging any error

slate swan
#
    @bot.command()
    async def roll(ctx, sides: int = 6):
        result = random.randint(1, sides)
        await ctx.send(f"You rolled a {result}!")
``` i got to this
hushed galleon
slate swan
#

async def roll(ctx, sides: int | None = 6): so this is correct

vocal laurel
slate swan
slate swan
#

thats why i want it optional

#

since it has a default value

vocal laurel
#

Ok

hushed galleon
#

if the only purpose is to make it optional but still raise any parsing errors, then Optional isnt necessary

vocal laurel
slate swan
#

so lib when parsing can skip it if not provided

hushed galleon
#

that is what the documentation describes its usage for

formal basin
#
ok_words2 = "badword"
    check_message = message.content.lower
    profanity_set = profanity.CENSOR_WORDSET

    message_without_spaces = check_message.replace(" ", "")
    for word in profanity_set:
     if word in message_without_spaces:
          if any (word in message.content.lower() for word in ok_words2):
              pass
     else:
            await message.delete()``` im making an anti swear in my bot and im trying to check if theres spaces in the CENSOR_WORDSET but this code is not working
sly blaze
#

Hey looking for some discord/python help. On windows the python script loads all fine, when i try to do it on ubuntu(python 3.11) i get some nonsence errors

trying all kinds of commands, cannot get the result can anyone help

naive briar
#

I won't call those nonsense

sly blaze
#

not nonsense, but in the end i cannot load the bot

shrewd apex
#

first of all it should be await bot.load_extension ur missing the await

#

2nd async def 1() what's that ๐Ÿ’€

sly blaze
thin raft
#

especially the "How to get answers"

thin raft
silk wasp
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     def 0():
003 |         ^
004 | SyntaxError: invalid syntax
silk wasp
naive briar
#

What???

silk wasp
# sly blaze

his function was

def l():

not def 1(): so it should work unlesss some error above

sly blaze
#

Sorted

silk wasp
#

ah ok]

sly blaze
#

updated code

naive briar
#

The error is pointing directly at the function declaration

dense barn
silk wasp
#

you know sometimes when it says invalid syntax and it point to a function it doesnt always means it the function it could mean the above code .-.

but whatever

naive briar
#

Then it would point to the above code, not the function

silk wasp
#

omg THAT HOW PYTHON FUNCTIOn

sorry

#

direct answer from chatgpt if u still wanna argue

Yes, you're correct. When you encounter an "invalid syntax" error in Python, the issue may not always be with the specific function indicated in the error message. It could be caused by a syntax error or inconsistency in the code above that particular function.

Python's error messages can sometimes be misleading in pinpointing the exact location of the error. It's important to carefully review the code preceding the function and check for any syntax errors or incorrect usage of keywords, operators, or punctuation.

If you encounter an "invalid syntax" error, it's a good practice to carefully review the code and check for any missing or misplaced brackets, parentheses, quotation marks, colons, or other syntax elements.

naive briar
#

You're already wrong by asking chatgpt

#

!e

@lambda _: 
def a(): ...
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     @lambda _: 
003 |                ^
004 | SyntaxError: invalid syntax
silk wasp
#

bro im give

you know what no point arguing

#

i let u win yes?

dense barn
naive briar
silk wasp
naive briar
#

I'm not arguing, I just told my point

naive briar
dense barn
#

Yes I guess.

thin raft
#

no spoon feeding

#

and btw

#

you do know channel permissions exist

#

I wouldn't want to be in that channel if people could connect tbh

#

you should make an admin role, and grant those to admins

#

you realise the join sound will still play for everyone

silk wasp
#

do u have a code u already setup i can teach u where u get wrong

thin raft
#

and what's you're issue?

#

your codes doesn't represent that

silk wasp
#

u never put .id after after.chanel

#

btw

#

if u finding after.channel == chanID

#

so did it fix?

#

hmm hold on

#

wait question is it in

@commands.Cog.listener()

#

ya

#

eh oh

#

then @client.event?

#

what is in your chanID

#

i mean you could do this instead

target_channel_id = YOUR_TARGET_CHANNEL_ID  # Replace with the ID of the specific channel
if after.channel and after.channel.id == target_channel_id and member.id not in allowList:
    await member.move_to(None)
#

just change target_channel_id to chanID

#

btw make sure your chanID is a int and not a str

#

heh

#

ok wait i i explain

#

wait first so lemme ask u few qn

did you join in a regular vc then join in the restricted vc or just straight up join the restricted vc

#

wait btw is the code work or did u change the chanID to int becos it was a str

#

so u never like cahnge anything to chanID

#

ah i see

#

so

silk wasp
#

confirm my last theory.-.

#

if i think you probably did this:

you straight up join the resitricted channel

#

becos your previous code

before.channel != after.channel checks if user switch channel not join channel

The condition before.channel != after.channel checks if the mebmer has switched voice channels. If that condition is true, it further checks if the after.channel.id matches the specified chanID and if the member's ID is in the allowList. If all conditions are met, it does nothing (pass). Otherwise, it moves the member to None (disconnects them).

#

so could u test this:

join a regular vc then join the restricted one see if it kick u

#

@slate swan

dense barn
silk wasp
#

i mean you could just add this and it will work flawlessly

elif before.channel and before.channel.id != restricted_channel_id and after.channel and after.channel.id == restricted_channel_id:
    if member.id not in whitelist:
            await member.move_to(None)

silk wasp
silk wasp
#

your previous command only check if user changes vc and did not include a way to check if user directly join vc

silk wasp
#

sure

silk wasp
silk wasp
#

change the YOUR_GUILD_ID to your guild id

#

@dense barn if it works lmk

swift edge
#

hey guys
who can show me a example of this

Enter Text:

what im looking for is im trying to make it where after the "Text:" theres text right after, when the user presses enter the text specified prints in the terminal

silk wasp
swift edge
#

ty

slate swan
#

Next time use an appropriate channel

dense barn
# silk wasp <@311172428049022978> if it works lmk

Uhm to clarify, I want it to be like this, for example. /char is a command then amber and other is something /char accepts so it spits out a specific embed. But still having /char without any arguments still be a valid command that spits out an embed. It works while using a prefix but using slash only shows the group_name subcommand's, in this case the /char amber and /char other.

slate swan
#

That's the limitation of slash commands

silk wasp
#

ok so u can add a main one first example:


@bot.slash_command(
    name="char",
    description="Get information about a character",
)
async def char(ctx):
    # Handle the case when no character name is provided
    await ctx.send("Please specify a character name.")

then uses
@char.sub_command()

@char.sub_command(
    name="amber",
    description="Get information about Amber character",
)
async def amber(ctx):
    # Logic for handling Amber character
    await ctx.send("Amber character information.")

IF that whay you mean

slate swan
#

You can't have

/char amber
/char other

and /char being a valid command as well

slate swan
#

Discord never allowed that

silk wasp
#

oh hmm

#

oh right right

silk wasp
#

ya no u cant

dense barn
#

okay seems it's not possible. so then I want char to accept a string and that will work. char will not be a command group anymore

so then I'd have to put all amber other inside my char command, right?

slate swan
#

Yeah pretty much

#

You can make it a string option with choices

dense barn
#

okay hmm then i'll make a dictionary with all the character details

#

okay that could work

#

it's going to be a long ass command

slate swan
#

Not necessarily

zenith ginkgo
#

ive been making discord bots for a few weeks now and i still havent got the discord dev badge eligbility

hasty pike
zenith ginkgo
#

it has to be 24 hours right?

hasty pike
zenith ginkgo
#

tyty

#

i dont see anything wrong. What does the output say

#

nothing im guessin

hasty pike
#

Neither showing out or error

#

It's just blank blank blank

zenith ginkgo
#

i was gonna suggest take a look at the auth

hasty pike
#

Also tried this

hasty pike
zenith ginkgo
hasty pike
#

What should i change there

zenith ginkgo
#

make it like that

hasty pike
#

Bot is private

#

Can't enable in app authorization

turbid condor
#

I don't think he needs admin perms just need perms to ban mem

slate swan
#

Administrator permissions

#

best permission to give 2023

zenith ginkgo
#

i give all my bots admin

slate swan
#

What a wonderful idea

zenith ginkgo
turbid condor
#

Then that doesn't mean u should suggest that to other's too

#

Permissions exist for some reason

hasty pike
#

It's okay he was just trying to help

zenith ginkgo
#

are you talking to me @turbid condor

turbid condor
#

Just telling u should not use admin perms for bots

zenith ginkgo
#

whys that

zenith ginkgo
turbid condor
#

Just in case if your token gets leaked and your bot has admin perms u should know what can happen in that case

zenith ginkgo
#

im just making prototypes in an isolated server as of right now

#

so i wouldnt know that

turbid condor
#

Then u should mess with perms so u should know what perms your bot actually needs

hasty pike
turbid condor
#

And literally event not listener

hasty pike
turbid condor
#

That's a listener not event

#

I mean ```py
@bot.event
async def on_mesaage(message):

hasty pike
#

Isn't it same?

#

Just a difference of main file and Cog

turbid condor
#

Nope event and listener are a bit different

#

U can even make a listener in main file

hasty pike
#

I don't think i used event anywhere

#

But i have on_message_edit aa a event

turbid condor
#

Then shouldn't be a problem since we need to look out for on_message only as it blocks the processing of commands if used in an event

hasty pike
#

Now what should i do

turbid condor
#

Can u try printing something in on your member ban listener to see if it is even being triggered

hasty pike
#

I tried

#

Right below async def line

#

It didn't execute either

#

That means function is not calling

turbid condor
#

Hmm

hasty pike
#

I remember it used to work when last time i worked on this project

#

Which was like 2 months ago

turbid condor
#

Can u use your bots help command to see if the commands in the on_member_ban cog are being listed

shrewd apex
#

u can have multiple listeners

#

but only a single event

hasty pike
#

I need to do sync first

#

Wait

#

I tried this too

#

I made a testing command in same Cog and command is working and listener isn't

turbid condor
hasty pike
#

This command is in same Cog too

shrewd apex
hasty pike
#

This command is responding but still didn't call listener

shrewd apex
#

u can decorate multiple callbacks with .listen()

#

show ur event listener

turbid condor
#

Cuz i remember my listener not working when i used them multiple times

hasty pike
#

@shrewd apex

hasty pike
shrewd apex
#

bro

#

why would u override an inbuilt event

#

u dont need to dispatch it

#

lib handles it internally

hasty pike
#

Dispatch for testing purposes

#

Ik it handles internally and that's why i made it

shrewd apex
#

try with a custom event then

hasty pike
#

But i gotta test it before doing final touch ups

hasty pike
#

It didn't even trigger when i actually banned a member using another bot

shrewd apex
#

do u have intent enabled?

hasty pike
#

So dispatch and naturally both ways aren't working

shrewd apex
#

for it?

#

server members intent

hasty pike
#

That's what i use

shrewd apex
#

thats weird

hasty pike
shrewd apex
#

are u receiving other on_member_* events?

#

can u try once

#

like join leave update etc

hasty pike
#

I'll try join

shrewd apex
#

hmm no idea tbh

hasty pike
#

I'll figure it out thanks for all the help

shrewd apex
#

there should be no specific reason for ban event to not work are the event and command both in same cog?

shrewd apex
#

also u sure the cog the event is in is loaded?

hasty pike
#

Yes testing command in it is working

#

Only event isn't triggering

shrewd apex
#

nothing even prints?

hasty pike
#

Nope

#

It isn't printing what i write, neither raising errors and nor giving me results

slate swan
#

put print("Loaded") in cog constructor and see if it is loaded for sure

hasty pike
slate swan
#

better to check twice

woven dew
#

how to send message link correctly?
i tried f'{msg.jump_url}' and f'<{msg.jump_url}>' but it doesnt work how i want
first generates annoying embed
second dont convert link to beatiful button

hasty pike
slate swan
woven dew
slate swan
#

put <> arround to get rid of embed

brisk bluff
#

i dont want to disrupt the convo but i have a doubt

#

dms?

slate swan
#

if you have any issues about discord bots topic ask here

hasty pike
#

@slate swan

brisk bluff
#

like not an issue but i have a normal python program
can i put that program in a discord bot so that basically instead of the stuff happening on IDLE it happens in a channel

shrewd apex
#

try banning a user with ctx.guild.ban to test i suppose

slate swan
hasty pike
slate swan
#

the event is indeed registered

hasty pike
slate swan
#

how do you judge if the event works?

glad cradle
#

is he using disnake?

slate swan
#

no idea, doesnt look like tho

woven dew
#

not good

hasty coral
#

Code:

async def set_channel(ctx, channel: discord.TextChannel):
    global response_channel
    response_channel = channel
    await ctx.send(f"Response channel set to: {channel.mention}")```

Error Message:
```Traceback (most recent call last):
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\jackf\Documents\Discord Counting Bot\counter.py", line 70, in on_message
    await ctx.send('Counting channel is not set. Use the `!set_channel` command to set it.')
NameError: name 'ctx' is not defined```

Anyone understand why?
woven dew
hasty pike
hasty coral
woven dew
#

show code

slate swan
#

or full command on this line

woven dew
#

show on_message function

hasty coral
slate swan
#

now full function associated with this

hasty coral
#
async def on_message(message):
    if message.author == bot.user:
        return

    content = message.content
    if content.isdigit():
        number = int(content)

    if response_channel:
        global current_number, finished
        if finished:
            await ctx.send("The counting game has already finished!")
            return

        if number == current_number + 1:
            current_number = number
            message = ctx.message
            await message.add_reaction('โœ…')
        else:
            await ctx.send(f"Oops! Wrong number. You entered {number}. The correct number was {current_number + 1}.")
            message = ctx.message
            await message.add_reaction('โŒ')
            finished = True
    else:
        await ctx.send('Counting channel is not set. Use the `!set_channel` command to set it.')```
hasty pike
hasty pike
slate swan
hasty coral
#

or define ctx as message

slate swan
#

no

#

in on_message you only get message witch is of type Message you cant get Context to it

#

if you want to send message use message.channel.send

hasty pike
hasty coral
#

@slate swan even though the message im typing in the chat is not an integer it is now sending the custom error message

hasty pike
hasty coral
#

i'll explain one second as there is no discord error message, it's my custom error message. But the code is picking up text instead of numbers.

#

My code:

async def on_message(message):
    if message.author == bot.user:
        return

    content = message.content
    if content.isdigit():
        number = int(content)

    if response_channel:
        global current_number, finished
        if finished:
            await message.channel.send("The counting game has already finished!")
            return

        if number == current_number + 1:
            current_number = number
            message = ctx.message
            await message.add_reaction('โœ…')
        else:
            await message.channel.send(f"Oops! Wrong number. You entered {number}. The correct number was {current_number + 1}.")
            message = ctx.message
            await message.add_reaction('โŒ')
            finished = True
    else:
        await message.channel.send('Counting channel is not set. Use the `!set_channel` command to set it.')```

The code is supposed to only be activated when a user types a number. But the code is activating when the used types a message that isn't a number.
#

The message the code is sending is Counting channel is not set. Use the !set_channel command to set it.

#

Nevermind, indentation error

tidal folio
slate swan
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.

hasty pike
hasty coral
#

I am having another issue.
So the bot checks if the message sent by a user is an integer, if so the bot sends a message, however this check is preventing my bot from sending responses for my other commands.

async def on_message(message):
    if message.author == bot.user:
        return

    content = message.content        
    if content.isdigit():
        number = int(content)```

Is there a separate line of code i need to add that allows the bot to send responses to other commands such as `!help`?
(There is no python error message)
zenith ginkgo
#

i have a weird question

#

everytime i stop the code in my IDE and then restart it

zenith ginkgo
#

it layers the instances

#

how do i stop this from happening

slate swan
#

how do you stop the code?

zenith ginkgo
#

yes

#

ive stopped it in my IDE

#

but it seems to keep going in my discord

slate swan
#

how do you stop the code?

zenith ginkgo
#

ik how to stop the code

#

but at the same time

#

i dont lmao

slate swan
#

can you answer my question or no?

#

im asking how do you stop your code?

zenith ginkgo
#

i press the stop button in VSC

#

whoch is wrong

slate swan
#

which one is it

#

you have to either kill the terminal running the bot or press Ctrl + C when focused on the terminal

sharp whale
#

how do i make it so only the command user can use the button

slate swan
unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
zenith ginkgo
#

ohh ok thank you

sharp whale
slate swan
sharp whale
#

uhh

#

can you show me an example

#

pls

slate swan
#
if ...: # check if user who clicked the button is the initial user
    return True
# send message that this user cannot use this view
return False
unkempt canyonBOT
#

bot/exts/info/subscribe.py lines 51 to 59

async def interaction_check(self, interaction: Interaction) -> bool:
    """Ensure that the user clicking the button is the member who invoked the command."""
    if interaction.user != self.interaction_owner:
        await interaction.response.send_message(
            ":x: This is not your command to react to!",
            ephemeral=True
        )
        return False
    return True```
slate swan
#

example from @unkempt canyon bot

sharp whale
#

hmm

formal basin
#
user = interaction.user.id #when the slash command is used
if interaction.user.id is not user: #in the button callback``` I use this
hasty pike
#

@slate swan Finally tried something and got an error

slate swan
hasty pike
#

'int' object has no attribute 'id'

slate swan
#

code?

hasty pike
formal basin
slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

hasty pike
slate swan
hasty pike
#

Nothing else

slate swan
slate swan
sharp whale
slate swan
sharp whale
#

2 line of code is better

#

i think

formal basin
slate swan
sharp whale
#

HMM

formal basin
#

after the if statement you need to do something

hasty pike
slate swan
#

then comment it out for now

hasty pike
#

It's not printing anything without error handler

hasty pike
slate swan
#

so you have more error handlers

zenith ginkgo
#

@slate swan i am very sorry, you have helped and shown me how to close the bot but the previous terminals are no longer there

#

so i cant close the,

hasty pike
formal basin
zenith ginkgo
#

ty

zenith ginkgo
slate swan
formal basin
formal basin
#

on the top right of the TERMINAL theres a bin sign

hasty pike
zenith ginkgo
formal basin
slate swan
hasty pike
slate swan
#

this is just try catch

hasty pike
#

I have nothing else except this

slate swan
#

instead of printing the exception do this

#

traceback.print_exc()

#

import traceback at the top obviously

stuck cosmos
#

does anyone know how to get the guild id of a server without CTX or Interactions?

stuck cosmos
formal basin
stuck cosmos
#

if yk what i mean

slate swan
#

i know what you want to do im asking how you want to get the guild id

#

from what

formal basin
stuck cosmos
#

i want this to be global so i can call it in other commands

stuck cosmos
#

with sqlite3.connect("freewlbot.db") as main:
         cursor = main.cursor()
         cursor.execute(f"SELECT ntoken FROM clusterinfo WHERE guild_id = ?", (discord.Guild.id,))
         nitoken = cursor.fetchone()
         nitoken = nitoken[0]
         header = {"Authorization": f"Bearer {nitoken}"}
         cursor.close()

stuck cosmos
slate swan
formal basin
slate swan
#

discord.Guild.id wont work

formal basin
#

its interaction.guild.id

stuck cosmos
hasty pike
#

@slate swan Got blank result

formal basin
stuck cosmos
#

if i add interaction it fucks wit it

slate swan
#
def add_to_database(guild):
    ...

@bot.command()
async def command(ctx):
    add_to_database(ctx.guild)
    ...
formal basin
#

or you could use global

slate swan
stuck cosmos
#

im technically not adding anything to the database, im just pulling the info

#

so i can use it in other commands

#

would i still use the same code?

formal basin
slate swan
slate swan
formal basin
#

ok

stuck cosmos
#

in code ive used ive never done that b4

slate swan
formal basin
stuck cosmos
#

no interaction for the setup

slate swan
stuck cosmos
#

the code im tryna use is above it, that will pull the info

formal basin
slate swan
#

full code?

stuck cosmos
#

and call it when needed

formal basin
stuck cosmos
#

i think thats what the code down sent dos

#

does*

mossy jacinth
#

How can i make the title a Link like in this screenshot? If its not possible in any way, is it possible to make it just blue?

formal basin
#

hmm I use redis db so idk sqlite

stuck cosmos
slate swan
#

!d discord.Embed.set_author

unkempt canyonBOT
#

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

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

you provide name url and icon if you want

stuck cosmos
midnight stirrup
#

How can I enable intents on the portal?

dense barn
#

my bot's doing this thing that even though the slash command worked, it's sending an error message. nothing's showing up on console.

mossy jacinth
slate swan
mossy jacinth
slate swan
mossy jacinth
#

Yeah I did that after the first attempt, forgot to remove it

#

I just tried if that worked

#

(it didnt)

slate swan
#

show full code sending the embed then

#

also no need to provide icon_url=None

#

its None by default

mossy jacinth
slate swan
# mossy jacinth

just tried it out it works for me but the link is not blue somehow

mossy jacinth
slate swan
#

oh i know

#

im dumb i told you wrong

#

it is title not author

#

when creating embed you can pass url kwarg

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if itโ€™s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

works now

mossy jacinth
dry kelp
midnight stirrup
slate swan
#

choose application you want go under Bot tab and scroll to Privileged Gateway Intents

dry kelp
#

is this just pylance being dumb?

#

and it's fine?

#

cause it's trying to edit an member

#

which makes no sense ๐Ÿค”

slate swan
#

whats that?

zenith ginkgo
#

why wont the bottom link update

dry kelp
zenith ginkgo
#

its the scope page

slate swan
slate swan
#

whats the GuildChannel class does it come from the library?

dry kelp
slate swan
#

what library are you using?

dry kelp
#

disnake

#

well i think it's not really an issue and code would still work fine, could be just pylance

#

i have it set on a high level

slate swan
#

well the GuildChannel does not indeed have the .edit method

zenith ginkgo
#

bc i finished it

dry kelp
#

@slate swan could you help me testing it?

#

or wait, i can with an alt

#

just curious how this would work

#

if it releases any errors

slate swan
#

actually you can skip this error since all classes that implement it have the .edit method

dry kelp
slate swan
#

but are you sure you want all channel types that exist?

dry kelp
#

I was about to tell you that

slate swan
#

not one specific?

#

like TextChannel

dry kelp
#

Well in this case yes, it's something i'm doing which is "antinuke" and it should trigger all of them

#

Nope, any channel deleted should be recreated

slate swan
#

okay then

dry kelp
#

taking the old channel position

#

so no matter if it's a stage channel or whatever

#

i was just unsure, pylance be triggering a lot of stuff

slate swan
#

pylance is not wrong but this wont run into any issues at runtime

#

weird that they dont have .edit message in this abstract class

#

@rocky grail we can ask disnake master why

dry kelp
#

he also contributed, really nice guy :)

dense barn
# slate swan code?

it seems to only be doing it when I use my import ViewMenu. I'm going to raise an issue on the github instead.

slate swan
dry kelp
#

How do you know? pithink

slate swan
#

cause he told me

dry kelp
#

oh lol

slate swan
#

also when we were doing one feature the issue with library happened and he raised an issue about it

dry kelp
#

๐Ÿ˜‚

stuck cosmos
#

Command 'setup' raised an exception: NameError: name 'header' is not defined

#

im still confused how to pull the info ๐Ÿ˜ญ

#

since i added ctx to get the guild id before, and the header is definded outside the command idk how to pull the info into the command

hasty coral
#

I have created a command to change the bot's prefix.
Although the command runs smoothly without errors, the bot's prefix stays the same.
Anyone know what im doing wrong?

Code snippet:

from discord.ext import commands

# Set the prefix for bot commands
prefix = "!"

# Create a bot instance
bot = commands.Bot(command_prefix=prefix)

@bot.command()
async def prefix(ctx, new_prefix):
    global prefix
    prefix = new_prefix
    embed = discord.Embed(title="Counter Prefix Set โœ…", description=f"The command prefix for Counter has been set to {new_prefix}", color=discord.Color.green())
    await ctx.send(embed=embed)```
zenith ginkgo
#

Please enter a redirect uri how do i get rid of this on the oauth2

alpine cove
#

you have to change the actual attribute

#

you are only changing the variable

hasty coral
alpine cove
#

check the github

#

!d discord.ext.commands.Bot.command_prefix

unkempt canyonBOT
#

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate โ€œdynamicโ€ command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as itโ€™s likely to cause performance issues and unintended command invocations.

zenith ginkgo
#

how do i fix this

#

the redirect uri

#

i need an url to add to server

stuck cosmos
#
async def gettoken(ctx):
     with sqlite3.connect("freewlbot.db") as main:
          cursor = main.cursor()
          cursor.execute(f"SELECT ntoken FROM clusterinfo WHERE guild_id = ?", (ctx.guild.id,))
          nitoken = cursor.fetchone()   
          nitoken = nitoken[0]
          **header** = {"Authorization": f"Bearer {nitoken}"}
          cursor.close()

@client.tree.command(name="setup")
async def embed(interaction: discord.Interaction, nitradotoken:str, freewlmapid:str):
        with sqlite3.connect("freewlbot.db") as db:
            cursor = db.cursor()
            cursor.execute(f"SELECT ntoken FROM clusterinfo WHERE guild_id = ?", (interaction.guild.id,))
            data = cursor.fetchall()
            if data:
                cursor.execute("UPDATE clusterinfo SET ntoken = ? WHERE guild_id = ? AND freewlmap = ?", (nitradotoken, interaction.guild.id, freewlmapid,))
                embed2 = discord.Embed(title=f"Successfully Updated Info")
                await interaction.response.send_message(embed=embed2)
            else: 
                  cursor.execute("INSERT INTO clusterinfo (ntoken, guild_id, freewlmap) VALUES (?,?,?)", (nitradotoken, interaction.guild.id, freewlmapid,))
                  db.commit()
                  embed3 = discord.Embed(description=f"Successfully Updated Info")
                  await interaction.response.send_message(embed=embed3)
            cursor.close()
            url1 = "https://api.nitrado.net/services"
            async with ClientSession() as session:
                 async with session.get(url1, headers=**header**) as response:

#

how would i get the header information above to go down to the request below?

#

down explained it earlier kind of but im still a bit confused

winter hare
zenith ginkgo
#

i just add the client id to this i fond on stack overflow

sick birch
sick birch
#

Can you show us?

winter hare
zenith ginkgo
winter hare
#

thats where u went wrong at

#

if u go through developer portal it will automatically generate a url

zenith ginkgo
winter hare
#

that wont work because theres no permissions given

#

just go through developer portal

slate swan
zenith ginkgo
#

i did that and still nothing

#

i just shut down my broweser and tried it again

#

after refreshing the page many many time

#

and its fixed

#

thank u guys and sorry for wasting your time

slate swan
#

What what did you check

#

Under scopes

winter hare
zenith ginkgo
#

just bot this time, should i do application commands too

slate swan
slate swan
hasty coral
#

I've created a counting bot. However, the score in one server, gets carried across to all other servers. Is there a way to log the score for each server individually?

#

By using a variable that only changes for the specific server that the command is executed in?

dry kelp
midnight stirrup
#

Could someone help me with placing my bot token into a different file apart from the main one? I did this but then got this error message.

turbid condor
#

This should import it

midnight stirrup
#

Okay, let me go try it. Thank you

midnight stirrup
turbid condor
#

Is the file containing the token in same folder as your main file?

midnight stirrup
#

It is in the same folder, yes

#

and this is the current error,

turbid condor
#

And how did u put Token in there?

midnight stirrup
#

Correct

turbid condor
#

I mean like Token = 'Your_bot_Token'like this

midnight stirrup
#

Like this?

turbid condor
#

Make the taken a string

midnight stirrup
#

I just put the ' around it

turbid condor
midnight stirrup
#

Okay, just around the token, yeah?

turbid condor
#

Yeah

#

Not the Token but token

midnight stirrup
#

Yeah, the long line of letters and numbers from the portal

#

That Token

turbid condor
#

Yup that one

midnight stirrup
#

Yeah, done that but still getting the same error message

#

Well actually, this comes up.

turbid condor
#

It means that the token is invalid try regenerating a new token and use that

midnight stirrup
#

Odd

#

And the token needs the ' around it?

torn solar
#

if i use @bot.command decorator will it also be a slash command

#

or do i need to use a different decorator

turbid condor
midnight stirrup
#

Alright, I'll be back

turbid condor
midnight stirrup
#

Should I show the code from it importing?

turbid condor
#

Yeah if u can

midnight stirrup
#

Top and bottom are for the token

turbid condor
#

The 'Token' is the problem u are passing it as a string

#

Remove the ' around it

turbid condor
midnight stirrup
#

Alright, fixed

desert hearth
#

could someone help me please

midnight stirrup
#

Still saying the same error message

turbid condor
#

Can u show me

turbid condor
midnight stirrup
#

Just removed the ' from (Token)

desert hearth
turbid condor
#

We won't be coding for u here but can explain what u need inorder to achieve it

desert hearth
turbid condor
midnight stirrup
#

Uh yeah?

turbid condor
#

Then what error is it throwing now?

midnight stirrup
#

The same damn one

turbid condor
midnight stirrup
#

Token = 'token here'

#

Here's what I have in apitoken

desert hearth
#

cos i said i could... i could...nt

turbid condor
turbid condor
midnight stirrup
#

I am so confused then

#

As a beginner, I did everything right

#

Maybe placing the token apart was a bad idea lol

turbid condor
desert hearth
midnight stirrup
desert hearth
#

ok ok sooo i got it working but its only giving 2 numbers, 4% and 12%

turbid condor
#

Ok can u show what u did?

desert hearth
#

but i think its giving the % in username chars

midnight stirrup
turbid condor
#

Achieve

midnight stirrup
#

๐Ÿ‘

turbid condor
#

As for u u can try setting up an .env

desert hearth
#

im assuming the coolness = len(member.display_name) % 100 is the way tit measures the % in the users name length?

turbid condor
desert hearth
turbid condor
#

Yup

desert hearth
#

awesome tyty

tall temple
#

hi guys

desert hearth
#

lemme test

tall temple
#

Please how can i generate a random number for every command called and not one time :

rn = random.randrange(1,2,1,2,1,2)

if number == rn and bet <= balance :
    embed = discord.Embed(title = "",
                        description = f":checkmark:  ใƒป  {nickname} won this game !\n\n> **Result :** `{balance}$` **โžœ** `{balance + bet}$` !",
                        color = 0x96ffa2)```
turbid condor
desert hearth
tall temple
turbid condor
tall temple
turbid condor
turbid condor
naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 100 0
002 | 101 1
003 | 102 2
004 | 103 3
005 | 104 4
006 | 105 5
007 | 106 6
008 | 107 7
009 | 108 8
010 | 109 9
011 | 110 10
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/kibohamoja.txt?noredirect

naive briar
desert hearth
#

so this?

naive briar
#

!e

import random

for _ in range(10):
    print(random.randrange(1, 2))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 1
003 | 1
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 1
010 | 1
tall temple
#

oh

#

!e

import random

for _ in range(10):
    print(random.randrange(1, 3))```
unkempt canyonBOT
#

@tall temple :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1
002 | 2
003 | 2
004 | 1
005 | 1
006 | 1
007 | 1
008 | 1
009 | 2
010 | 1
tall temple
#

okok lemme test

turbid condor
desert hearth
tall temple
#

still not working

turbid condor
tall temple
#

i need to generate a new random number for every called command

naive briar
desert hearth
turbid condor
turbid condor
#

Like 1,10 will generate from 1 to 10

naive briar
#

How would 1, 10 generate from 0, 10

tall temple
turbid condor
naive briar
#

What is it then

turbid condor
#

Then??

turbid condor
#

And what would what i said will do?

tall temple
#

?

naive briar
naive briar
#

And?

tall temple
turbid condor
#

And what is the problem??

tall temple
#

Damn

turbid condor
#

If u are using randint(1,2) u should know it's completely random

tall temple
#

I want to generate different random numbers for each executed command

turbid condor
#

U can't calculate how many times 1 will come or 2 will come

tall temple
torn solar
#

how can i pass a member through @bot.command()

sick birch
torn solar
#

just a member

#

like @ ing a member

sick birch
#

You typehint an argument to be : discord.Member

torn solar
#

ty

turbid condor
#

Like between which two numbers should that be generated?

tall temple
#

I want a random number thatโ€™s generated on every command call

turbid condor
#

So like if u and me are playing i get the number 860 and u get 740 or something?

turbid condor
#

Then u can make two different variables and send one two each

#

Like

tall temple
#

Gimme an example

turbid condor
#
Number_1= random.randint(0,100)
number_2=random.randint(0,100)
#

And the send it use number_1 in the message that is for u and number_2 for the other person this will give both of u different number

naive briar
#

It can also give the same number

turbid condor
torn solar
#

do i need to register commands

#

if so how do i

turbid condor
#

If it's slash_commands u need to sync them

torn solar
#

i figured it out

torn solar
naive briar
#

Then send the error

turbid condor
#

Is that a local_image?

torn solar
#

error is to big to send

naive briar
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

torn solar
#

and yeah the image is local and so is the path

naive briar
#

!d discord.File - the file argument only accept this object

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
turbid condor
#

Then u need to pass it through dscord.File first and then send

torn solar
#

is fp file path

#

and is there a way to do it as a url

#

not path

turbid condor
torn solar
#

how can i do a urll tho

turbid condor
torn solar
#

ah ty

turbid condor
#

Like รญ post the picture to a discord channel and then copy the link of that picture and use that

torn solar
#

embed.set_thumbnail(member.display_avatar)

#

how can i get their avatar as a url too

#

cus set_thumbnail only takes urls

turbid condor
#

embed.set_thumbnail(url=member.display_avatar)

torn solar
#

oh

#

im stupid sorry

torn solar
#

!paste

#

async def announce(ctx, title, color= discord.Color,*args): description = ''.join(args) embed = discord.Embed(title=title, color=color, description=description)

vocal snow
#

discord.Color is a class

#

You need to pass an instance of it

#

Not the class itself

#

If you don't want to set a color then pass None

winter token
#
@commands.command()
    async def bal(self, ctx):
        
        with open('data.json', 'r') as f:
            data = f.read()
        
        if ctx.author.id not in data:

            with open('data.json', 'w') as f:
                
                data[id] = ctx.author.id

            json.dump(data, f)
#

Error occured: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'data.json'

twilit grotto
#

can you show your full project structure, like your file structuring

twilit grotto
#

which file is your command in, economy?

winter token
#

whats the error

twilit grotto
#

i think your messages intent needs to be message_content not 'messages'

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

twilit grotto
#

error?

#

does your bot have the correct permissions needed to update members?