#discord-bots

1 messages · Page 133 of 1

slate swan
#

well you can do that in the Transformer s but the interaction still gets recieved

cloud dawn
soft radish
#
Traceback (most recent call last):
  File "main.py", line 67, in <module>
    client.run(os.getenv("Token"))
  File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
  File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))```
slate swan
#

your token is invalid most probably

soft radish
slate swan
#

then you have been ratelimited

#

reason: replit
solution: kill 1 in shell

soft radish
#

what does that do?

atomic delta
#

trying to create discord bot.. help 😦 ?

slate swan
#

change .event on on_message to .listen()

slate swan
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 Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

slate swan
#

see the alternative commands

#

venv\Scripts\Activate.ps1
venv\Scripts\activate.bat

atomic delta
#

still not working

slate swan
#

i said .listen(), not .listen

#

oh mb

primal token
#

and why are you using time.sleep?

slate swan
#

😔 im a .listener()

primal token
loud junco
#

is there any better hosting site that doesnt need credit card

#

oracle and digitalocean needs credit card ;-;

slate swan
primal token
#

!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:
primal token
#

use this

molten cave
#

does anyone know how i can make my bot ping me like this when i make a command ?

slate swan
#

!d discord.AllowedMentions

unkempt canyonBOT
#

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.

This class can be set during [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
loud junco
slate swan
#

whatever method you use, use allowed_mentions= that object above

loud junco
#

btw

molten cave
loud junco
molten cave
#

lemme try that

loud junco
slate swan
loud junco
#

oo

#

i dont have json :D

slate swan
#

do you save any files locally?

loud junco
#

no

#

100% code

slate swan
#

then you can use that

#

gotta create a github repo for it tho

loud junco
#

:/

slate swan
#
Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

loud junco
slate swan
#

its only for hosting

loud junco
#

im literall going to watch a tutorial for githb repo

slate swan
#

its as easy as sending a file on discord

loud junco
#

hmm

#

i hope so

#

i have PBD :D

tough lance
#

Off topic, but when did discord started giving these new badges?

pastel basin
#

How can I host multiple bots (tokens) in one file?

pastel basin
tough lance
pastel basin
#

How tho?

mighty yarrow
#

@client.command(pass_context=True)
async def createall(ctx):
await ctx.message.delete()
for guild in client.guilds:
try:
link = await ctx.channel.create_invite(max_age = 0)
print("Creating invite link")
except:
pass

#

how to create every server invite links that bot in?

molten cave
#

!random

#

where are the random choice docs

#

@slate swan how do i make random choice from random numbers up to 1000

loud junco
#

where should i save my token in vs code hmmmmm

slate swan
#

!d random.randint * sorry

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
slate swan
loud junco
molten cave
slate swan
#

add it to gitignore

loud junco
slate swan
#

pgsql

loud junco
#

i mean like website

slate swan
#

what db do you use

pastel basin
loud junco
#

about to make one

upbeat gust
loud junco
#

cuz im not gonna use my pc to host :D

upbeat gust
#

how is that relevant

loud junco
upbeat gust
#

On the host?

loud junco
#
Railway

Railway is an infrastructure platform where you can provision infrastructure, develop with that infrastructure locally, and then deploy to the cloud.

#

i dont think they have a database

upbeat gust
loud junco
#

which one do u think i should use

slate swan
#

pgsql ( postgresql)

#

i have used their mysql service and it is pretty nice so i think it should be same for pgsql

loud junco
loud junco
slate swan
#

yeah seems normal

upbeat gust
#

that's like an env file

slate swan
#

those are envs for that server

#

every railway application has that

upbeat gust
slate swan
loud junco
slate swan
#

The db should have some details about your credentials

loud junco
#

do i need to create a new project for db?

upbeat gust
#

Yes

loud junco
#

ok

upbeat gust
#

A db is a seperate server

loud junco
#

so i should have 2 thing in my dashboard?

upbeat gust
#

Unless you use sqlite

#

Although idk if you can here

slate swan
loud junco
#

looks healthy?

slate swan
#

yes

#

now go to that server and get the credentials

loud junco
#

whats credentials

slate swan
#

password username etc for the database

slate swan
# loud junco

the connect tab has ur credentials or variables one mb

upbeat gust
#

It's probably under connect

loud junco
#

i found this

upbeat gust
#

Yes

loud junco
#

i dont need to change any of them right?

#

just copy

slate swan
#

you'll just need the DATABASE _URL to connect usually

#

yes just copy the URL thing

loud junco
#

ok

molten cave
#

im trying to make my bot look like this however the embed looks like this my bot is second

loud junco
#

i dont even know how to link the database to my bot

#

do u all have any docs?

slate swan
#

!pip asyncpg

unkempt canyonBOT
slate swan
#

bruh nvm

loud junco
slate swan
#

upto you

loud junco
#

it works that way?

molten cave
#

where are the docs for def check(m)

upbeat gust
#

???

molten cave
#

oh

upbeat gust
#

what docs do you even need

#

All you do is return true or false

loud junco
#
import asyncio
import asyncpg
from aiohttp import web


async def handle(request):
    """Handle incoming requests."""
    pool = request.app['pool']
    power = int(request.match_info.get('power', 10))

    # Take a connection from the pool.
    async with pool.acquire() as connection:
        # Open a transaction.
        async with connection.transaction():
            # Run the query passing the request argument.
            result = await connection.fetchval('select 2 ^ $1', power)
            return web.Response(
                text="2 ^ {} is {}".format(power, result))


async def init_app():
    """Initialize the application server."""
    app = web.Application()
    # Create a database connection pool
    app['pool'] = await asyncpg.create_pool(database='postgres', user='postgres')
    # Configure service routes
    app.router.add_route('GET', '/{power:\d+}', handle)
    app.router.add_route('GET', '/', handle)
    return app


loop = asyncio.get_event_loop()
app = loop.run_until_complete(init_app())
web.run_app(app)
```i copied something i dont understand at all
#

who told me its free :/

slate swan
#

thats not how you use it lol, i have a mysql bot example but idk if that will help

loud junco
#

idk how to do it ;-;

slate swan
#

the bot is in hikari now you gonna migrate to that too lol?

shrewd apex
#

aiomysql when?

loud junco
#

but i have 0 idea on how to connect db

shrewd apex
#

try asyncpg i can give u an example

loud junco
#

im not asking someone to spoonfeed me but i literally dont know

loud junco
unkempt canyonBOT
#

core/bot.py lines 85 to 93

self.database_pool: aiomysql.Pool = await aiomysql.create_pool(
    host=os.getenv("MYSQLHOST"),
    user=os.getenv("MYSQLUSER"),
    db=os.getenv("MYSQLDATABASE"),
    password=os.getenv("MYSQLPASSWORD"),
    port=int(os.getenv("MYSQLPORT") or "0000"),
    loop=asyncio.get_event_loop(),
    autocommit=False,
)  # getting configs from the .env file and setting up the database```
shrewd apex
#

or aiomysql

slate swan
#

fk no Mongodb

loud junco
#

pool = request.app['pool']?

#

this is how u set it up?

#

what is the 'pool' tho

slate swan
loud junco
slate swan
#

first choose what db you wanna use
ill find an example

shrewd apex
loud junco
#

like a bunch of arranged wire from phone to pc?

shrewd apex
#

managed*

loud junco
#

its the same :D

shrewd apex
#

its handled internally in the library

loud junco
shrewd apex
#

all sql dbs are the same

slate swan
#

^

shrewd apex
#

nothing easier or tougher

loud junco
#

i have choice makig difficulties

#

hmm

slate swan
#

just use pgsql

shrewd apex
#

i would say go asyncpg personal preference

loud junco
#

then pg

slate swan
#

!pip asyncpg this has examples

unkempt canyonBOT
slate swan
#

read the readme

loud junco
#

ok

slate swan
loud junco
#

Or to perform multiple operations on a single connection:
what does it mean by 'multiple operations on a single connection'

slate swan
#

using same connection for multiple queries

loud junco
#

ok

#

its not ticking

upbeat otter
#

yes

loud junco
#

:/

upbeat otter
#

what's the issue

loud junco
#

its not ticking

upbeat otter
loud junco
#

oo :D

upbeat otter
#

ticking? what's not ticking lmao

#

also, it's saying to select "director" of EACH film not get all the directors

slate swan
#

my brain's not ticking

slate swan
loud junco
#

i have no idea what are u talking about so ye

loud junco
slate swan
upbeat otter
slate swan
#

y'all nasty

loud junco
#

:/

#

since when osama bin laden joins coding

upbeat otter
#

not only in mc lmao

upbeat otter
loud junco
#

20tps

#

💀

#

alr lets stop before some random dude !ot

#

GTA is 120tb???

slate swan
#

Hello,
I need a help I am trying to make a simple embed command with normal message like mimu bot can someone help me

loud junco
#

1 tb = 1024gb?

#

ye

#

like 0.1 sec

cloud dawn
loud junco
#

ye

loud junco
#
import asyncpg

async def db():
  async with asyncpg.create_pool(user='postgres', command_timeout=60) as pool:
    await pool.fetch('SELECT 1')
```is this how u do it?
slate swan
#

depends on a lot of things but yes

#

if you can postpone the db for sometime i can write a note about how to use a database with your bot and send it to you

loud junco
#

postpone?

slate swan
#

start using it after some time

loud junco
#

sure

slate swan
#

basically wait for sometime

#

ight ill do it when im home

loud junco
#

nobody is going to use it anyways

slate swan
loud junco
slate swan
#

no worries im already making a bot that uses pgsql so that would be easy

loud junco
#

YAY

loud junco
upbeat otter
vale wing
#

I am gonna have to reinstall my ubuntu on the server cuz 22.10 has performance issues and weird bugs

upbeat otter
vale wing
#

All my bots lagging today 😡

loud junco
vale wing
#

Stoopid 22.10

loud junco
#

-pip install discord?

upbeat otter
#

discord is an unmaintained mirror package

loud junco
#

can i do it in termial :D

upbeat otter
#

sure

#

anywhere that supports pip

loud junco
#

ok thaks

#

my keyboard is kind of ded

slate swan
simple kettle
#

I want to add a cooldown on a command. I’m wondering how I want to go about it

loud junco
loud junco
simple kettle
loud junco
#

ye

#

try storing the time in database ig

slate swan
simple kettle
#

That’s what I was thinking

loud junco
#

aight

slate swan
placid skiff
loud junco
loud junco
placid skiff
#

you will have to recreate every cooldown for every user with their specific remaining time

loud junco
#

fr?

placid skiff
#

and after the cooldown has done you will have to delete that cooldown

loud junco
#

isnt that gonna wreck the whole database 💀

placid skiff
#

tbh it will be a waste of time

#

consider that you will even need to calc the time that is passed from when the bot has gone offline and when it reconnects to keep a real time cooldown

loud junco
#

why not just let it be

#

let it reset after restart

simple kettle
placid skiff
#

yup that's what i was telling there

#

tbh it's a really hard work

loud junco
#

why not just save all the command last used time as a list

placid skiff
#

and it's not worth it

simple kettle
loud junco
#

and compare it to irl time

simple kettle
#

Think I got a idea that makes it really simple

placid skiff
#

I suggest you to create your own cooldowns

#

make it independent from the bot and database dependent

#

create a custom check that retrieves the time from the db

tacit sentinel
#
def give_rank(rank=["Trades: 0", "Trades: 5", "Trades: 20", "Trades: 35", "Trades: 50", "Trades: 75"]):
    @client.event
    async def on_message(message):
        if message.content == "CALC":
            if v_MN[0] > 0: 
                pos = [0,5,20,35,50,75].index(v_MN[0])
                role = get(message.author.guild.roles, name=rank[pos])
                await message.author.add_roles(role)```
placid skiff
#

and raise an error if there is still time left before can cast the command again

tacit sentinel
#

Can someone fix this code? v_MN[0] is just a number of Trades.

placid skiff
#

what is the error?D_D

tacit sentinel
#

I think I am also not supposed to call client.event inside the function.

simple kettle
#

Does python have something where you can input a time and it will tell you how long it’s been since then

tacit sentinel
placid skiff
#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
placid skiff
#

you will need this to make date operation

#

you can check online the other things that you need

placid skiff
#

tbh everything is wrong in that code

#

you need to study python more

mighty yarrow
#

@client.command(pass_context=True)
async def cinviteall(ctx):
await ctx.message.delete()
for guild in client.guilds:
try:
link = await ctx.channel.create_invite(max_age = 0)
print("Creating invite link")
except:
pass

#

help

loud junco
mighty yarrow
#

how can i create invite link on every server that bot in

loud junco
#
if isinstance(error, commands.CommandOnCooldown):
    seccd = round(error.cooldown.get_retry_after())
    mincd = 0
    hrcd = 0
    rseccd = 0
    rmincd = 0

    if seccd > 59:  
      
      rseccd = int(seccd % 60)
      mincd = int((seccd - rseccd) / 60)
      if mincd > 59:
        rmincd = int(mincd % 60)
        hrcd = int((mincd - rmincd) / 60)
    else:
      rseccd = seccd
    await ctx.send(f'''
Dont spam :/ 
Try again in another **{hrcd}h {rmincd}m {rseccd}s**
''')
placid skiff
#

wtf is that

loud junco
loud junco
#

ik it looks quite dumb but hey it works

naive briar
#

There's something called divmod

placid skiff
unkempt canyonBOT
#

@placid skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.

0:05:00
placid skiff
loud junco
#

ahem

loud junco
naive briar
#

What

molten cave
#

using slash commands and got this error

#

lmk if u need my code

mighty pilot
#

Is there a "contains" argument where I could say if user input contains h, multiply the number before by 3600 (to get seconds for sleep), same for minutes and days

mighty pilot
calm jacinth
#

can someone teach me how to make a discord bot ;-;

placid skiff
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

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

Message.mentions returns a list of Member that were mentioned in the message

molten cave
mighty pilot
# molten cave i moved it down same error

It's best to put sync inside of a command. On_ready isn't complete the moment the code is read, it takes a few seconds for the bot to connect to discord and exchange information to determine that its ready

#

Maybe making it sleep for 10 seconds or something would be sufficient, not sure as I haven't tried it that way. I usually just have it print something in my console when it's ready so I know I can then sync

molten cave
#

you want me to sleep the bot for 10 secs after on ready alr

mighty pilot
#

Show me what you got

molten cave
#

thats my on ready

#

@mighty pilot my tree command

hollow gazelle
#

Exception has occurred: AttributeError
'Bot' object has no attribute 'slash_command'.

#
import pycord
bot = commands.Bot(command_prefix=".",case_insensitive=True,intents=intents)
@bot.slash_command
mighty pilot
shrewd apex
#

🗿🗿

rustic edge
#

Is there a way to restart my Discord bot from inside the script itself? Instead of having to kill the script then somehow re-enabling it.

rustic edge
#

Yep.

hollow gazelle
#

Yes u can

rustic edge
#

Any documentation on it?

minor totem
mighty pilot
# molten cave the channel id?

No, the application ID, that's something that's usually passed during the login() part of the code. Are you overriding anything else besides on_ready?

minor totem
hollow gazelle
mighty pilot
#

!d discord.Client.application_id

unkempt canyonBOT
#

property application_id```
The client’s application ID.

If this is not passed via `__init__` then this is retrieved through the gateway when an event contains the data or after a call to [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"). Usually after [`on_connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_connect "discord.on_connect") is called.

New in version 2.0.
minor totem
rustic edge
molten cave
#

what

mighty pilot
#

Shouldn't need to be there, I just didn't know where he was syncing, inside or out of the on_ready. That seems to be ruled out so the error says it's something wrong with his application_id

minor totem
rustic edge
#

How would I go around doing that?

minor totem
# molten cave what

If something is designed to be awaited, then the code inside of it doesn't run until you do await it. This means that your bot won't actually sleep unless you await it correctly

molten cave
#

yeah i fixed that but i still cant peform my slash command

#

same errir

minor totem
# rustic edge How would I go around doing that?

You can use sys.exit() if you first import sys, this will ensure the process exits. Depending on your setup, it may make more sense to just shut down the bot and then let the rest of the code run until it completes.

rustic edge
#

My problem is how I would start the bot again.

minor totem
rustic edge
minor totem
rustic edge
#

no

minor totem
#

Okay well I recommend you set that up because it will also ensure that the bot never shuts down.

#

Hmm, another option would wrapping your bot in a little script which restarts the bot if it exited with a special error code. That's assuming you don't want to setup automatic restarting in any other case.

mighty pilot
#

Cron jobs ftw

#

That mentions whoever used the command

#

Author is the author of the command

minor totem
minor totem
#

Do you want to grab the mention from the command? Do you have a strong which you know contains only the mention?

mighty pilot
#

Are you using slash commands?

mighty pilot
molten cave
#

wont work

#

oh wait it says forbidden access lemme fix the server

mighty pilot
azure granite
#

ayo bro pls remind me how to change server in replit

#

cz rate limit

#

kk

mighty pilot
#

That link I send above this message has an example of how to use a converter to accomplish what you're trying to do

#

Look at the example for the userinfo command

azure granite
#

i dont get why it does not work

#

i dont get

slate swan
#

what lol

slate swan
azure granite
#

how u mean me to use it

azure granite
slate swan
# azure granite what ?

ctx.message.content checks the full content, if you'll use ctx.message.content on a command it will show
<the prefix you used><the command you used> <the argument your provided>

#

which definitely wont be "on" in a command

azure granite
#

hmm yea

#

im the arguement is on

#

wait lemme send what i typed

slate swan
#

that's what i said, message is the variable you store the argument in

azure granite
slate swan
#

so you'll do message == "on"

#

¯_(ツ)_/¯

azure granite
#

well i will try

azure granite
#

this is right ?

slate swan
#

just a plain message=="on"

azure granite
#

nope still , doesnt ctx refers to command ?

slate swan
azure granite
#

it WORKS

slate swan
#

okay bro show example of what you mean.

#

!d discord.Colour.green

unkempt canyonBOT
#

classmethod green()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x2ecc71`.
slate swan
#

0x22ecc71

#

its already async code lol

azure granite
slate swan
azure granite
#

i see

slate swan
#

for example if you have py @command() async def ping(ctx): ... when someone used !ping on discord, a ctx is created based on the context in which the message with !ping was created

#

it stores information such has the server, message, author etc

azure granite
#

ohhh now im getting it

mighty pilot
#

Hey @slate swan, is there a way to see if a slash command argument contains xxH for example? Like if someone puts in 24h I could check for H and multiply the 24*3600 for a sleep time?

#

Trying to find a way to avoid making seperate command arguments for days, hours, minutes, etc

slate swan
#

!pip durations-nlp

unkempt canyonBOT
mighty pilot
#

Regex, gross DMpuke I'll check out that library though thanks

slate swan
#

it will basically convert inputs like "5m 10s" to a datetime object

mighty pilot
#

Sweet

slate swan
#

yes field values cant be empty

#

use \u200b instead

#

anywhere you want an empty block

mighty pilot
#

Is it the empty description field? Just don't include it

whole sparrow
#

how to get member object from user's tag

#

e.g. get member object from Anom4ly#5426

mighty pilot
#

Oh I guess you can use just the username or ID as well

mighty pilot
#

pikafacewow I'm saving that one

maiden fable
mighty pilot
slate swan
#

yo would anyone mind helping me

#

i cant get my bot to import discord

#

or

#

from discord.ext import commands do that

prisma prism
#

Hi Guys!

unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

slate swan
#

!docs discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

prisma prism
#

My bot needs to work in only specific channels,

@bot.event
async def on_message(message):
    msg = message.content
    if "!" in msg:
        if message.channel.id in (471304870335479810,989634034713907253,994243878355996785):
            await bot.process_commands(message)
        else:
            print("Not correct channel, so not doing aything")
                  
#

Will this work? and limit all commands to only work in those specific channels?
or is there a better way of doing it?

mighty pilot
#

If it works send it. Give it a try and if you get errors come back here

naive briar
#

msg is undefined

#

And you should use checks instead, in case you don't want some commands to be limited

prisma prism
#

thanks, I realised and added the line that defines msg

prisma prism
honest shoal
honest shoal
slate swan
honest shoal
slate swan
#

oh so i should install that

#

alr

honest shoal
slate swan
#

i have already done that

prisma prism
honest shoal
#

restart vs code?

slate swan
#

wont work i have already tested that many times

naive briar
unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
honest shoal
naive briar
#

There's example there

slate swan
#

it was pretty long ago i did a bot

honest shoal
#

and show the result

slate swan
#

there

honest shoal
# slate swan

on which python version is this installed and which python version are u using on vs code?

slate swan
#

i think it was

#

3.11.0

honest shoal
#

don't guess, check both cases

slate swan
#

bu ti know its that

#

bc i saw that when i downloaded it

honest shoal
#

those 2 were the most common cases

slate swan
#

ok

#

ty tho

honest shoal
#

0x2ecc71

#

why

#

that's just a hexcode

sick birch
#

!d discord.Colour.green

unkempt canyonBOT
#

classmethod green()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x2ecc71`.
sick birch
#

Use these factory methods

honest shoal
#

you can use hexcode if you want better green

#

show error

#

or the code if no error

#

can u paste it here and send 👇

unkempt canyonBOT
#

Pasting large amounts of code

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

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

honest shoal
#

how r u invoking the command

#

us this error handler then py @bot.listen('on_command_error') async def error_handler(ctx, error): raise error

#

strange

#

is the bot having permissions wherever u are testing

#

like view channel, send msgs

#

elaborate

#

because it had no issues

slate swan
#

hex codes are 6-digits, you entered a 7-digit code here

radiant parrot
#

my image for my embed thumbnail field is nvr loading?

#

any reason why this wld happen

slate swan
#

you might have entered the url incorrectly

ocean dragon
#

are there menus / pagination in pycord? I need to print a list of strings that might be longer than allowed 2000 characters, so I might want pagination

slate swan
#

yes there's discord.ext.pages iirc

#

or soemthing like that

slate swan
#

how can I install discord_components?

slate swan
fading marlin
#

dpy has components, there's no need to install forks

slate swan
unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

slate swan
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

idky i added s there lol

stone quest
slate swan
#

CL_AwkwardStand maybe, thats basically like dict.update so yeah

#

!d nextcord.PermissionOverwrite.update

unkempt canyonBOT
#

update(**kwargs)```
Bulk updates this permission overwrite object.

Allows you to set multiple attributes by using keyword arguments. The names must be equivalent to the properties listed. Extraneous key/value pairs will be silently ignored.
slate swan
#

yes

fading marlin
#

you can do PermissionsOverwrite(manage_members=True) instead

stone quest
#

yeah but i have them formatted from dict

stone quest
fading marlin
stone quest
#

i dont get where it says A list of key/value pairs to bulk update with.

slate swan
stone quest
slate swan
#

what errror

stone quest
#

Command raised an exception: TypeError: update() takes 1 positional argument but 2 were given

#

so its like, .update("manage_members", True)?

fading marlin
#

update takes **kwargs, not a dictionary

stone quest
#

damn

fading marlin
stone quest
#

oh wait i literally can do that?

fading marlin
#

thought I still don't get why you'd use update

fading marlin
stone quest
#

bulk updating perms

#

how would you do it? always open to constructive criticism

fading marlin
#

you can instantiate PermissionsOverwrite and pass in the same arguments you would to update

stone quest
#

see i was unsure about that so I just made sure

#

but thanks for clarifying 👍 will do that

#

will test now, thanks Lee

fading marlin
#

no problem

slate swan
#
Traceback (most recent call last):
  File "C:\Users\jpjan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\jpjan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\jpjan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'add_roles'
#
to_add = discord.utils.find(lambda r: r.id == 1041008296888385576, ctx.guild.roles)
                    await user.add_roles(to_add)
#

Someone help

fading marlin
slate swan
#

i mention user on my guild

#
@commands.command()
    async def addlicense(self, ctx, user: discord.User = None, date=None):
        if ctx.author.id == 985170190121730120:
            if user == None:
                
            else:
                if date == None:
                    
                else:
                    to_add = discord.utils.find(lambda r: r.id == 1041008296888385576, ctx.guild.roles)
                    await user.add_roles(to_add)
        else:
            
fading marlin
#

you need a Member, not a user

slate swan
#

oh ok, how?

naive briar
#

Change the type hint to member

vale wing
naive briar
#

When the you

civic oak
#

anyone have ideas for my bot im french but not needed just dm me

vale wing
slate swan
#

loooli i installed my operating system with both the password and the confirmation password wrong and now im trapped

radiant parrot
#

why r my images not loading when put into a thumbnail embed?

#

just constantly to the loading thing

naive briar
#

Is the url correct

radiant parrot
#

Yes

#

If i press open original it works

#

just wnt work in embed

slate swan
#

Someone have script that can change discord name and icon with command?

hushed galleon
left dagger
#

yall

#

i can a question

#

so im new to coding and working with discord bots

#

so please go easy on me

#

is it possible to code a bot that send custom messages to members in a specific server?

#

Please ping me if someone is willing to help

wicked atlas
#

can you send the rest of your code?

austere vale
#
  @commands.Cog.listener()
  async def on_command_error(self,ctx,error):
    try:
      if hasattr(ctx.command, 'on_error') or ctx.command is None:
        return
      else:
        embed=nextcord.Embed(title=f'Error in {ctx.command}',description=f'`{ctx.command.qualified_name} {ctx.command.signature}`\n{error}', color=0xfd9fa1)
        await ctx.send(embed=embed)
    except:
      embed=nextcord.Embed(title=f'Error in {ctx.command}',description=f'{error}', color=0xfd9fa1)
      await ctx.send(embed=embed)

is there a way to change this so that errors will get printed to BOTH the terminal and the discord channel, instead of only the discord channel?

left dagger
wicked atlas
austere vale
left dagger
wicked atlas
#

discord.py will only log internal errors and stuff automatically iirc, so you would have to do my_logger.error(error) or something in your handler

wicked atlas
#

!d discord.Member.send

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

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

anyone help me do some bot math?

#

I have an xp system

austere vale
#

thank you am2i9

slate swan
#

40/220 how can I calculate how much % the user has competed? like make it equal 18.18% (which is the %)

wicked atlas
#
(40/220) * 100
slate swan
#

You- multiple by 100... pepecringe2

#

so take xp then divide by the max xp they need then times a 100 ok ok

#

thanks

wicked atlas
#

yep, that's how you find a percentage

slate swan
#

thanks

#

how do I send emojis in embeds?

#

this doesnt work

wicked atlas
#

If i remember correctly, there are a few parts of an embed that don't support message formatting like that, the title being one of them

slate swan
#

i tried description

#

would footer?

wicked atlas
#

description should be able to

slate swan
wicked atlas
#

hmm, maybe you can't

slate swan
#

ig so

#

i can use footers

wicked atlas
#

it works in the footer?

slate swan
#

yea

#

idk wait

#

it works with fields ik that

slate swan
#

me to 💀

radiant parrot
hushed galleon
#

right click on the image and look for a "copy image link" option or similar, that should give you the actual image url you can use in your embed

slate swan
wicked atlas
slate swan
#

but im trying to do emojis from other servers and stuff

wicked atlas
#

is the bot in those servers?

slate swan
#

no

wicked atlas
#

then it can't use them

slate swan
#

u can use emojis in servers the bot isnt it

#

no true. technically you can

#

using the <a:name:id>

#

but not like this

#

nah thats the format for animated emojis

#

yes it is

wicked atlas
#

I've never seen that work tbh

slate swan
#

explain this

#

explain what?

#

there animated

#

u said its not the format for them

#

yeah thats an animated emoji?

#

oh i read wrong

#

yeeee

#

nvm lol

#

whats for non animated emojis?

wicked atlas
#

remove the a

slate swan
#

remove the a

#

it still works with the a

shrewd merlin
#

how do I get a users message? is it message.content?
heres my code
@bot.command() async def add(message): userid = message.author.id print(userid) message = message.content print(message)

but I get this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'content'?

sick birch
#

Because the first argument is always the context, you just named it wrong

#

If you changed it to ctx like it should be, then it's ctx.message.content

shrewd merlin
#

Ahhh ok

#

Thank you

#

And for everyone's knowledge, I am new so don't be rude

abstract kindle
#

where do you guys store tasks?

alpine cove
slate swan
#
async def add(ctx, *numbers):
   await ctx.send(f"Result: {sum([*map(int, numbers)])}")
#

i hope it works

alpine cove
#

if you want the user to be able to add as many numbers as they wish go for smth like:

async def one_line_try(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except:
        return None

@bot.command()
async def add(ctx, numbers = None):
    if not numbers:
        await ctx.send("Please provide at least one number!")
        return
    if not (s := one_line_try(map, int, *numbers.split())):
        ctx.send("Please provide valid numbers!")
        return
    ctx.send(f"Result: {sum(s)}!")
alpine cove
#

weird

shrewd merlin
#

You guys are amazing.

#

It works, now I need it to be user mistake proof. So lets say someone types in !add 500'

#

or 500y
or anything that is followed by something that is not an integer

pliant gulch
#

!d str.isdigit

unkempt canyonBOT
#

str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
shrewd merlin
#

How do I single the integer out in the line

pliant gulch
#

If you want to extract integers it'll be easiest to regex or you can for-loop over with a buffer and check for isdigit

shrewd merlin
#

Ah gotcha roger that

alpine cove
#

at least it should be lol

#

but rather use on_error

abstract kindle
#
for character in string:
  if character.isdigit() is False:
    string.strip(character)
``` Something like this?
#

Actually that

#

I'm bad xD

alpine cove
#
async def add(ctx, *numbers):
   await ctx.send(f"Result: {sum([*map(int, numbers)])}")

@add.on_error
async def add_error(error, ctx):
    if isinstance(error, TypeError):
        await ctx.send("Provide valid numbers next time!")
    else:
        await ctx.send("Internal error")
pliant gulch
#

You couldn't just filter with isinstance then cast

alpine cove
slate swan
#
  random_xp = random.randint(1, 15)
  if random_chance == 1:
    rubyadd = random.randint(3)
    random_chance = str(f'+ {rubyadd}')
  else:
    random_chance = str('')
  rubyadd = rubyadd * rubymulti
  random_xp = random_xp * xpmulti
  random_mny = random_mny * moneymulti
  levelup = ''
  xp = users[f'{user.id}']['xp'] + random_xp
  if xp >= xp2:
    level = users[f'{user.id}']['level'] + 1  

why wont this add anything to my xp?

abstract kindle
#

@slate swan just for the future, id recommend using a database rather than a json file to store user data

#

sqlite is perfect for small projects and easy to learn

slate swan
#

...

#

Code:

from discord import app_commands 

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

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

@client.event
async def on_ready():
    print('bot online!')

@client.event
async def on_message():
    channel = client.get_all_channel(1041527847396835338)
    await channel.send(description=f"{on_message}")

Error:

TypeError: on_message() takes 0 positional arguments but 1 was given```
abstract kindle
# slate swan ...

I know it sucks, but trust me it will save you pain later down the road

slate swan
#

@slate swan

#

on_message(message)

#

then do message.content instead of on_message

#

oh now it works I have tried that previously but I got an error

#

u did it wrong then

#

any good yt vids?

#

thats basically the only way I can learn

#
Traceback (most recent call last):
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\dynam\Documents\badge\badge.py", line 18, in on_message
    channel = client.get_all_channel(1041527847396835338)
AttributeError: 'aclient' object has no attribute 'get_all_channel``` 

When I turned into that this is what I got
#

client.get_chnanel(id)

slate swan
# slate swan client.get_chnanel(id)
async def on_message(message):
    channel = aclient.get_chnanel(id)(1041527847396835338)
    await channel.send(description=f"{message.content}")```

So this?
#

no

#

replace that with
client.get_channel(1041527847396835338)

#

so no channel =?

#

no keep that

#
async def on_message(message):
    channel = client.get_channel(1041527847396835338)
    await channel.send(description=f"{message.content}")```
#

yea

alpine cove
#

ur just gonna get rate limited

fading marlin
#

get_channel doesn't do api calls

slate swan
alpine cove
fading marlin
#

it gets the channel from cache

fading marlin
slate swan
#

cache

alpine cove
slate swan
#

hold up so what do I fix lemon_swag

fading marlin
alpine cove
alpine cove
slate swan
#
async def on_message(message):
    channel = client.get_channel(1041527847396835338)
    await channel.send("{message.content}")```

This code sends like 5 messages from one message from my selected channel id.
Anyway I can change it up a bit to prevent getting rate limited
fading marlin
fading marlin
sick birch
#

commands.Bot don't have this issue, so that's one solution
Another solution is to just add a simple if statement check:

if message.author == client.user:
  return
fading marlin
#

or just use a logger

slate swan
#

What can I remove so it doesn't keep triggering the evemt

#

event*

fading marlin
slate swan
#

do I have to be on pc to use sqlite

#

i cant download the thing to see the db

fading marlin
#

sqlite is a file-based database, so you have to be in the device that has the file to check the database

slate swan
#

@client.event
async def on_message(message):
if message.author != client.user:
channel = client.get_channel(1041527847396835338)
await channel.send("{message.content}")

fading marlin
abstract kindle
#

@slate swan what IDE do you use?

slate swan
#

replit

#

...

abstract kindle
#

you use replit to edit your code?

slate swan
#

yea? Im on a school chromebook 🥺

abstract kindle
#

I see

slate swan
#

its hard

slate swan
#

sqlite seems rlly easy actually

abstract kindle
#

it is extremely easy. and I like to use peewee as my ORM. Just as easy

slate swan
#

english?

abstract kindle
#

ORMs are useful for translating class objects into database rows

slate swan
#

no german

#

whats a way i can do this with replit

abstract kindle
#

you can do all of this with replit, as long as you can create an sqlite file on your pc

#

and as long as you can install packages

slate swan
# slate swan <@456226577798135808>

When I type in any channel in my server it sends to the id in my code which is good but I want it a message from the ID I selected is there a way to fix this?

#

yea

#

@slate swan explain more

slate swan
# slate swan <@456226577798135808> explain more

When I send a message in a random channel in my server it sends to 1041527847396835338 the id where the bot sends the messages.

What I want to do is get channel ids from different servers and the bot sends the message to1041527847396835338

#

oh easy

#

one sec

#

okay

#

I want to get messages from multiple channel ids

#
@client.event
async def on_message(message):
    if message.author != client.user:
      if message.channel.id == channnelid or message.channel.id == id:
        channel = client.get_channel(1041527847396835338)
        await channel.send("{message.content}") 
#

just replace id with your id

slate swan
#

where do I put the id where the messages go

#

@slate swan i suggest you learn some stuff

#

its pretty obvious

#

you replace channelid and id...

fading marlin
#

would anyone like to give me a bit of feedback on a project I've been working on?

fading marlin
#

would you mind a DM? I don't think I'm allowed to send it here

fading marlin
#

thank you! :)

slate swan
fading marlin
#

where did you add the f?

primal token
#

You probably havent saved the codes new state and you dont even need it

slate swan
#

(f"{message.content}")

fading marlin
#

f"{...}"

#

you don't need the f string either way

#

message.content returns a string

slate swan
#

Oh okay, but how can I fix it so the bot doesn't send {message.content}

#

@fading marlin ?

fading marlin
slate swan
# fading marlin what does your code look like now?
async def on_message(message):
    if message.author != client.user:
      if message.channel.id == 1041527847396835338 or message.channel.id == 1041476774531432480:
        channel = client.get_channel(1041854560156782613)
        await channel.send("{message.content}") ```
fading marlin
#

remove the whole string, you don't need it. Just send message.content

slate swan
#

It works just fine just only problem is {message.content}

fading marlin
#

remove the string, keep message.content

fading marlin
#

it's my take on a jsk-like extension

slate swan
#

ohh I'd like to check it out

slate swan
#

is it the same as the one in ur bio?

fading marlin
#

yep :)

fading marlin
slate swan
# fading marlin now it's a set, you gotta remove the {}
async def on_message(message):
    if message.author != client.user:
      if message.channel.id == 1041527847396835338 or message.channel.id == 1041476774531432480:
        channel = client.get_channel(1041854560156782613)
        channel.send(message.content) ```

Still does the same thing
fading marlin
#

now you're not awaiting channel.send

#

also, message.channel.id == ... or message.channel.id == ... is unnecessary, you're checking the exact same condition

slate swan
#

well zioqh helped with that

fading marlin
#

oh, sorry, I didn't see that they were different ids

#

consider checking if it's inside a tuple instead, it'll save you some spaghetti code

primal token
#

A set would be better

slate swan
# fading marlin oh, sorry, I didn't see that they were different ids
Traceback (most recent call last):
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\dynam\Documents\badge\badge.py", line 21, in on_message
    await channel.send(message.content)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1536, in send
    data = await state.http.send_message(channel.id, params=params)
  File "C:\Users\dynam\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```

Is what I got once added `await`
fading marlin
#

do you have message content intent enabled?

slate swan
slate swan
#

documentation as in a readthedocs/mkdcos/github wiki page

slate swan
#

@fading marlin

  random_xp = random.randint(1, 15)
  if random_chance == 1:
    rubyadd = random.randint(3)
    random_chance = str(f'+ {rubyadd}')
  else:
    random_chance = str('')
  rubyadd = rubyadd * rubymulti
  random_xp = random_xp * xpmulti
  random_mny = random_mny * moneymulti
  levelup = ''
  xp = users[f'{user.id}']['xp'] + random_xp
#

do i need += to add scores?

#

becuase this doesnt work

fading marlin
fading marlin
slate swan
#

what r ur intents

#

for the code

fading marlin
slate swan
slate swan
#
@mt.tree.command(name='pick', description='Use your pickaxe to mine!')    
async def mine(interaction: discord.Interaction):
  user = interaction.user
  with open("users.json", "r") as f:
    users = json.load(f)
  xp = users[f'{user.id}']['xp']
  level = users[f'{user.id}']['level']
  rubys = users[f'{user.id}']['rubys']
  money = users[f'{user.id}']['money']
  xp2 = users[f'{user.id}']['xp2']
  pick = users[f'{user.id}']['pick']
  moneymulti = users[f'{user.id}']['moneymulti']
  rubymulti = users[f'{user.id}']['rubymulti']
  xpmulti = users[f'{user.id}']['xpmulti']
  rubyadd = ''
  random_mny = random.randint(1, 100)
  random_chance = random.randint(1, 100)
  random_xp = random.randint(1, 15)
  if random_chance == 1:
    rubyadd = random.randint(3)
    random_chance = str(f'+ {rubyadd}')
  else:
    random_chance = str('')
  rubyadd = rubyadd * rubymulti
  random_xp = random_xp * xpmulti
  random_mny = random_mny * moneymulti
  levelup = ''
  xp = users[f'{user.id}']['xp'] + random_xp
  if xp >= xp2:
    level = users[f'{user.id}']['level'] + 1   
    levelup = str(f"Leved up to level {level}!")
  embed = discord.Embed(title=f'Mined with Pickaxe Level {pick}', description=random.choice(random_help))
  embed.add_field(name='You Got', value=f'{levelup}\n:money_with_wings: {money} + {random_mny}\n{rubys} {rubyadd}')
  view = View()
  view.add_item(mt.select)
  await interaction.response.send_message(embed=embed,view=view, ephemeral=True)

this is the whole code

fading marlin
slate swan
#

oh i never dumped them

fading marlin
slate swan
#

nah I got it

#

I never dumped the json in the fike

slate swan
fading marlin
#

probably why you should be using an sql database

slate swan
#

idk if i can

#

as i am not on an actually pc]

fading marlin
fading marlin
unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
fading marlin
#

Intents.default does not include message content

slate swan
fading marlin
#

yes

slate swan
fading marlin
#

you have to define a variable that points to Intents.default before you call super().__init__

slate swan
#

I don't understand

fading marlin
#

before ||(the line above)|| you call super().__init__, you have to define your intents and pass those into your constructor

slate swan
#

I don't really know how to define the intents

fading marlin
#

create a new variable?

hollow gazelle
#

Traceback (most recent call last):
File "d:\yew\main.py", line 4, in <module>
from discord import commands
File "C:\Users\rhino\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands_init_.py", line 27, in <module>
from .core import *
File "C:\Users\rhino\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 54, in <module>
from .options import Option, OptionChoice
File "C:\Users\rhino\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\options.py", line 27, in <module>
from ..enums import ChannelType, SlashCommandOptionType
ImportError: cannot import name 'SlashCommandOptionType' from 'discord.enums' (C:\Users\rhino\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\enums.py)

#

who can help

slate swan
fading marlin
#

I'm assuming you know how to make a new variable right?

hollow gazelle
#
Traceback (most recent call last):
  File "D:\yew\main.py", line 57, in <module>
    @bot.slash_command(name="stock", description="Allows you to see the current token stock and boost stock!")
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
Press any key to continue . . .
#

i need help

slate swan
fading marlin
slate swan
fading marlin
hollow gazelle
slate swan
#

or a value

fading marlin
#

what?

#

do you know where you're calling super().__init__?

slate swan
#

intents I don't really know how to respond

sick birch
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

Lee do you know a way where the bot automatically adds @everyone infront of the message the bot gets from the channel ids?

fading marlin
#

just prepend @everyone to the message's content

mighty pilot
#

Norow you should read some documents

#

Just put @everyone in the message the bot sends

slate swan
slate swan
#
  random_mny = random.randint(1, 100)
  random_chance = random.randint(1, 100)
  random_xp = random.randint(1, 15)
  if random_chance == 1:
    rubyadd = random.randint(3)
    random_chance = str(f'+ {rubyadd}')
  else:
    random_chance = str('')
  rubyadd = rubyadd * rubymulti
  random_xp = random_xp * xpmulti
  random_mny = random_mny * moneymulti
  levelup = ''
  xp = users[f'{user.id}']['xp'] + random_xp
  if xp >= xp2:
    level = users[f'{user.id}']['level'] + 1   
    levelup = str(f"Leved up to level {level}!")
  with open("users.json", "w") as f:
    json.dump(users, f)
#

this doesnt add anything to my scores someone help pls

slate swan
#

bruh

#
@client.event
async def on_message(message):
    msg = message.content
    if message.author != client.user:
      if message.channel.id == 1041527847396835338 or message.channel.id == 1041476774531432480:
        channel = client.get_channel(1041854560156782613)
        await channel.send(f"@everyone >> {message.author} >> {msg}") 
mighty pilot
#

It is that easy

slate swan
#

u dont even need {msg}

#

just added it

slate swan
mighty pilot
#

Yea one sec

fading marlin
slate swan
#

alr thx

mighty pilot
#

No promises I know what's up with it lol

slate swan
#

hm?

slate swan
#

i dont know when too much is too much

mighty pilot
slate swan
#

ill send the full code

#
@mt.tree.command(name='pick', description='Use your pickaxe to mine!')    
async def mine(interaction: discord.Interaction):
  user = interaction.user
  with open("users.json", "r") as f:
    users = json.load(f)
  xp = users[f'{user.id}']['xp']
  level = users[f'{user.id}']['level']
  rubys = users[f'{user.id}']['rubys']
  money = users[f'{user.id}']['money']
  xp2 = users[f'{user.id}']['xp2']
  pick = users[f'{user.id}']['pick']
  moneymulti = users[f'{user.id}']['moneymulti']
  rubymulti = users[f'{user.id}']['rubymulti']
  xpmulti = users[f'{user.id}']['xpmulti']
  rubyadd = ''
  random_mny = random.randint(1, 100)
  random_chance = random.randint(1, 100)
  random_xp = random.randint(1, 15)
  if random_chance == 1:
    rubyadd = random.randint(1, 3)
    random_chance = str(f'+ {rubyadd}')
  else:
    random_chance = str('')
  rubyadd = rubyadd * rubymulti
  random_xp = random_xp * xpmulti
  random_mny = random_mny * moneymulti
  levelup = ''
  xp = users[f'{user.id}']['xp'] + random_xp
  if xp >= xp2:
    level = users[f'{user.id}']['level'] + 1   
    levelup = str(f"Leved up to level {level}!")
  with open("users.json", "w") as f:
    json.dump(users, f)
  embed = discord.Embed(title=f'Mined with Pickaxe Level {pick}', description=random.choice(random_help))
  embed.add_field(name='You Got', value=f'{levelup}\n:money_with_wings: {money} + {random_mny}\n{rubys} {rubyadd}')
  view = View()
  view.add_item(mt.select)
  await interaction.response.send_message(embed=embed,view=view, ephemeral=True)
mighty pilot
#

Can you use randint(3)? Like does that take one number?

slate swan
#

ohhh wait

#

i meant 1, 3

#

but it still doesnt work

mighty pilot
#

Well rubyadd seems to be in a lot of things and it's value is ''

slate swan
#

wait how can it be a integer then?

mighty pilot
#

Wym

#

Is there any specific value that it's not doing?

#

Like does it show all the values in the level up embed

slate swan
#

if random_chance is one then ruby add is a random integer from 1 to 3 which is then multiplied by your multiplier

mighty pilot
#

I understand that. But which value in all of those doesn't seem to be working

#

You said some score wasn't being added to

#

part of your else in your if/else isnt indented properly

#

rubyadd

#

thats probably what it is if youre not getting that last value in your embed{rubyadd} to be what you expect

slate swan
#

so remove the else:?

mighty pilot
#

No just indent the rubyadd line under else properly

slate swan
#

ill test it

#
@xi.tree.command(name='leave', description='Leave Guild!')
@app_commands.describe(guild_name = 'Pick a guild')
async def lev(interaction: discord.Interaction, guild_name: str):
  if interaction.user.id != 1031053618008301588:
    await interaction.response.send_message("Cant Do this command", ephemeral=True)
    guild = discord.utils.get(xi.guilds, name=guild_name)
    if guild == None:
        print("No guild with that name found.") # No guild found
    if guild != None:
      await interaction.response.send_message(f"I left: {guild.name}!")
      await xi.leave_guild(guild) # Guild found
#

why doesnt this work?

#

it says its already been responded too before

mighty pilot
#

Because you're sending 2 interaction.response messages

slate swan
#

oh yea wait

mighty pilot
slate swan
#
async def on_message(message):
    if message.author != client.user:
      if message.channel.id == 1034897577478455337 or message.channel.id == 1025864145150685194:
        channel = client.get_channel(1041876398849146910)
        await channel.send(f"@everyone {message.content}") ```

Anyone know a method where I can add more channel ids that the bot reads and sends to my channel?
#

await xi.guild.leave(guild) # Guild found

#

yea u copy what i put dude

#

please learn python a little before this

slate swan
#

do i need the guild id?

mighty pilot
#

yea u copy what the docs say, please learn to read docs a little before this

slate swan
#

read it

slate swan
#

i looked it up and didnt find it

slate swan
#

docs?

#

What is even happening 💀

#

idk I asked an question but uh uh

mighty pilot
#

he made a remark about someone learning python before asking for help, then asked for help himself so i followed up with a remark about being able to read the docs

mighty pilot
#

people gotta start somewhere

slate swan
#

i was told not to spoon feed him 💀

mighty pilot
#

well you can help without spoonfeeding and without patronizing

slate swan
#

Because I want to add more ids

#

copy that...

#

@mighty pilot where is it on the docs i cant find it

#

What are you looking for in the docs?

#

how to leave guilds

#

stack overflow came in clutch ngl

#

await guild.leave()

#

I typed leave into the docs search-bar and discord.Guild.leave is the 2nd result. That is probably what you're after.

#

i forgot i defined guild 💀

mighty pilot
slate swan
#

i need help w something tho rn

slate swan
radiant parrot
#

How do i assign a unique url to each value in an embed?

slate swan
#

wait i think i got it

#

im making guild configs

#

like bad words, ect

slate swan
radiant parrot
#

But atm its assigning one url to all fields

slate swan
#

but I think I got it
when they setup configs if there id is not in a file create a file with the guild id, then add stuff and when its on_message open the file with the message.guild.id var and then check it all

#

and if its not in there it wont do anything

slate swan
radiant parrot
# slate swan Can you send the code for your embed?
for sizeValue in secondArray:
    string = ""
    idsformatted = ('\n'.join(sizeValue))
    string += f"{idsformatted}\n"
    embed.add_embed_field(name='Size/VariantID', value=f'[{string}](https://google.com?{variantID})\n')
    pass```
slate swan
#

then just do {link}

#

if thats what u mean

slate swan
radiant parrot
#

as have 10 variantids

slate swan
#

Well what is variantID?

radiant parrot
radiant parrot
slate swan
#
async def on_message(message):
    if message.author != client.user:
      channellist = [1034897577478455337, 1025864145150685194, 1038870393815044257, 1033090064827306086]
      if message.channel.id in channellist:
       
        channel = client.get_channel(1041876398849146910)
        await channel.send(f"@everyone {message.content}") ```

So I have this and I want the ids in `channellist` to send to my channel how can I code that to happen right under `if message.channel.id in channellist:` ?
#
@mt.tree.command(name='configs', description='Check your configs!')
async def configs(interaction: discord.Interaction):
  with open("configs.json", "r") as f:
    guilds = json.load(f)
  with open('guilds.txt') as file:
    guildid = file.read().split()
    if interaction.guild.id != guildid:
      await update_guild(guilds, interaction.guild)
      with open("guilds.txt", "a") as f:
        f.write(f"{interaction.guild.id}\n")

why does this still write the guildid?

obtuse blaze
#

await self.user.send(f"You have been kicked from {interaction.guild} for {self.reason.value}")
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

    def __init__(self,user) -> None:
        super().__init__()
        self.user = user
    reason = discord.ui.TextInput(
        label = "Reason",
        placeholder = "Reason For Kick",
        style = discord.TextStyle.long,
        required = True,
        min_length = 1,
        max_length = 1000
    )
    async def on_submit(self, interaction: discord.Interaction):
        await interaction.guild.kick(self.user,reason=self.reason.value)
        await interaction.user.send(f"You have kicked {self.user} for {self.reason.value}")
        await self.user.send(f"You have been kicked from {interaction.guild} for {self.reason.value}")
        embed = discord.Embed(title="Kick", description=f"You have been kicked from {interaction.guild.name}", color=discord.Color.red())
        embed.add_field(name="Reason", value=self.reason.value)
        await interaction.response.send_message(embed=embed)```
```@discord.ui.button(label='Deny User', style=discord.ButtonStyle.grey)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(ReasonKick(self.user))
        self.value = False
        self.stop()```

```async def Checkuser(self,interaction,proof):
        embed = discord.Embed(title="Verification", description=f"User: {interaction.user.mention} ID: {interaction.user.id}", color=discord.Color.green())
        embed.set_image(url=proof)
        view = Confirm(interaction.user, interaction, proof)
        await interaction.guild.get_channel(1030517888232210462).send(embed=embed,view=view)```

I put how self.user is get so it makes more sense
#

anyways I can't get why im getting the error when the user doesnt have dms locked nor bot blocked

slate swan
# radiant parrot a like 9 long integer

So you want to insert a different integer into the URL where variantID is each time the for loop code runs, so that each URL is unique. I'd just create a list containing your '10 variants' and iterate through that list when the for loop runs. Or you could use randint or something to generate your integer, I don't know how you want to do it.

slate swan
obtuse blaze
#

oh bruh im dumb

slate swan
#

Happens to the best of us from time to time based

slate swan
mighty pilot
slate swan
#

yea i got it dw

jovial lynx
#

Hi there can somebody point me in the right direction of a bot?
I need a discord bot with 2 functions;

  1. responds to all messages in #wallpapers with "⭐"
  2. responds to all messages in #wallpaper_requests with "✅" and "❌"
slate swan