#discord-bots
1 messages · Page 133 of 1
Yeah I meant that the interaction gets blocked and that you can send a custom error message.
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'))```
your token is invalid most probably
it was working a while ago
resets the IP ( one of things that it does )
change .event on on_message to .listen()
!venv
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
no you listen
and why are you using time.sleep?
😔 im a .listener()

is there any better hosting site that doesnt need credit card
oracle and digitalocean needs credit card ;-;
so it sleeps before deleting the message ?
!d asyncio.sleep
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:
use this
does anyone know how i can make my bot ping me like this when i make a command ?
!d discord.AllowedMentions
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.
add f'<@{ctx.author.id}>' KEKW
whatever method you use, use allowed_mentions= that object above
btw
i want it to ping anyone who uses the command
is there any better hosting site that doesnt need credit card
oracle and digitalocean needs credit card ;-;
lemme try that
@molten cave
railway but it will delete your json and stuff if you have any, it keeps only static code
do you save any files locally?
:/
there is no editor in it?
its only for hosting
i see
im literall going to watch a tutorial for githb repo
its as easy as sending a file on discord
Off topic, but when did discord started giving these new badges?
How can I host multiple bots (tokens) in one file?
Few days ago
I just wanna try
Not recommended but you can try multiprocessing
How tho?
@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?
!random
where are the random choice docs
@slate swan how do i make random choice from random numbers up to 1000
where should i save my token in vs code hmmmmm
!d random.choice
!d random.randint * sorry
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
random.randint(0,1000)
a .env file
.env file wont be visible in github repo?
ty
add it to gitignore
btw any online database that u would recommend?
pgsql
i mean like website
what db do you use
nvm i got the code
Why website??
cuz im not gonna use my pc to host :D
how is that relevant
then where should i do it
On the host?
im using https://railway.app
i dont think they have a database
They have postgres mongo and mysql
pgsql ( postgresql)
i have used their mysql service and it is pretty nice so i think it should be same for pgsql
ok
btw is this the database
yeah seems normal
..do you know what a database is..?
wait is that the python app you create or the db app?
ik but i cant find it
The db should have some details about your credentials
do i need to create a new project for db?
Yes
ok
A db is a seperate server
so i should have 2 thing in my dashboard?
create new project and choose postgresql
looks healthy?
password username etc for the database
the connect tab has ur credentials or variables one mb
It's probably under connect
Yes
ok
im trying to make my bot look like this however the embed looks like this my bot is second
!pip asyncpg
the first one is `number`, you have ```number```
bruh nvm
upto you
it works that way?
where are the docs for def check(m)
oh
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 :/
thats not how you use it lol, i have a mysql bot example but idk if that will help
idk how to do it ;-;
im going for mysql then
KEKW
the bot is in hikari now you gonna migrate to that too lol?
aiomysql when?
no 💀
but i have 0 idea on how to connect db
try asyncpg i can give u an example
im not asking someone to spoonfeed me but i literally dont know
there is only mysql pgSQL redis and mongo
create a pool and store it in a botvar
https://github.com/sarthhh/anya/blob/main/core/bot.py#L85-L93
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```
fk no Mongodb
.
that example is not for discord bots
oo i see
first choose what db you wanna use
ill find an example
consider it a ordered and systematic collection of connections to a db
i see
like a bunch of arranged wire from phone to pc?
managed*
its the same :D
its handled internally in the library
help me pick the easiest :D
all sql dbs are the same
^
nothing easier or tougher
just use pgsql
i would say go asyncpg personal preference
then pg
!pip asyncpg this has examples
read the readme
ok
Or to perform multiple operations on a single connection:
what does it mean by 'multiple operations on a single connection'
using same connection for multiple queries
learn sql first https://sqlbolt.com
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
yes
:/
what's the issue
its not ticking
plus this is not #databases
oo :D
ticking? what's not ticking lmao
also, it's saying to select "director" of EACH film not get all the directors
my brain's not ticking
asyncpg is pgsql asyncpg is just a lib for postgres
:D
i have no idea what are u talking about so ye
if ur brain is ticking then maybe u are going to have some hard time
? you said ur only options where blah blah pgsql. do you know what pgsql is ? lol
💀 I swear I thought "ticking" means something related to tick rate
i have no idea
y'all nasty
not only in mc lmao
you made me 😳
Hello,
I need a help I am trying to make a simple embed command with normal message like mimu bot can someone help me
Just make it Discord bot related.
ye
im back after learning some basic
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?
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
postpone?
start using it after some time
sure
nobody is going to use it anyways

thanks ❤️
no worries im already making a bot that uses pgsql so that would be easy
YAY
do i need to have discord.py installed tho
you need to get a 299 lmao, go study 💀 (apologies for reminding)
I am gonna have to reinstall my ubuntu on the server cuz 22.10 has performance issues and weird bugs
¯_(ツ)_/¯ ofc
All my bots lagging today 😡
aight
Stoopid 22.10
-pip install discord?
can i do it in termial :D
i have a break till 7:45 🦆
LMAOOO 299/100?
I want to add a cooldown on a command. I’m wondering how I want to go about it
i dont need uptimerobot if i use railway right?
@commands.cooldown(1, 1, commands.BucketType.user)
Yeah but doesn’t that cooldown get reset if the bot gets reset?
nope you don't
That’s what I was thinking
aight
300
lmao you will have to handle it anyways
its 247?
wdym 👀
you will have to recreate every cooldown for every user with their specific remaining time
fr?
and after the cooldown has done you will have to delete that cooldown
isnt that gonna wreck the whole database 💀
Did not think about that
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
Well I still want cooldowns to keep going down as the bot is down
why not just save all the command last used time as a list
and it's not worth it
Well I could just have another program to mange the database
and compare it to irl time
Think I got a idea that makes it really simple
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
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)```
and raise an error if there is still time left before can cast the command again
Can someone fix this code? v_MN[0] is just a number of Trades.
what is the error?
I think I am also not supposed to call client.event inside the function.
Does python have something where you can input a time and it will tell you how long it’s been since then
None. Just no output.
!d datetime.timedelta
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...
you will need this to make date operation
you can check online the other things that you need
why do you have an event inside a function? how it is supposed to be called?
tbh everything is wrong in that code
you need to study python more
@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
let me show u a masterpiece that is quite garbage
how can i create invite link on every server that bot in
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**
''')
wtf is that
I am making a discord bot in discord.py, py-cord, and I was wondering if it's possible to have the bot generate a discord invite for a server and send it to you and how to do it?
Is it possible?
An...
There's something called divmod
!e
import datetime
print(datetime.timedelta(seconds=300))
@placid skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
0:05:00

ahem
AHEM
What
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
You can't call tree.sync until on_ready is complete
can someone teach me how to make a discord bot ;-;
!d discord.Message.add_reaction
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`.
Message.mentions returns a list of Member that were mentioned in the message
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
you want me to sleep the bot for 10 secs after on ready alr
Show me what you got
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
Well it wasn't passed before on_ready so it's gotta be the other part of the error, something up with the Application ID
the channel id?
🗿🗿
Any help
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.
Like a command restart ?
Yep.
Yes u can
Any documentation on it?
Why do you want to restart the bot? There's different things you can restart
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?
Are you sure you have imported everything correctly? I think you should import pycord before the other import
Igh thanks I’ll check it out
!d discord.Client.application_id
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.
You don't await asyncio.sleep(10) so it essentially never happens
Because I'm running my bot on my NAS, so what I do, is run a command through discord to pull the latest code from the Github repo, then I want to restart the bot to implement the changes.
what
That was added in later anyways it wasn't there to begin with
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
Depending on framework, you could just re-import the updated files, but the easiest way is to just exit the bot completely.
Does your bot automatically restart if it shuts down? That would be set up in your host
How would I go around doing that?
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
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.
My problem is how I would start the bot again.
What is tree defined as here? Shouldn't you use client.tree?
Yes, but then how would I start the bot?
If your host is setup to restart no matter what happens, then you can let it do that. That's why I asked whether your host did automatically restart
no
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.
Cron jobs ftw
That mentions whoever used the command
Author is the author of the command
Haha yeah, personally in my setup I run a Docker compose network which has a restart of always
I need to learn docker yet 
Do you want to grab the mention from the command? Do you have a strong which you know contains only the mention?
Are you using slash commands?
You may be able to use this, I'm not 100% sure https://discordpy.readthedocs.io/en/stable/api.html?highlight=mentions#discord.Message.mentions
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
what lol
if message == "on"
how u mean me to use it
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
that's what i said, message is the variable you store the argument in
well i will try
nope still , doesnt ctx refers to command ?
ctx refers to the command invocation context, it isnt related to the argument!
it WORKS
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`.
ohk so its kind of that when i use ctx , it automatically considers it as a command
its quite the opposite, when you create a command
a context around the command invocation is created and is provided to the command function
i see
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
ohhh now im getting it
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
use regex, a convertor or use durations-nlp library
!pip durations-nlp
Regex, gross
I'll check out that library though thanks
it will basically convert inputs like "5m 10s" to a datetime object
Sweet
Is it the empty description field? Just don't include it
If you @ tag them you could use converters as seen here
Oh I guess you can use just the username or ID as well
!d discord.ext.comands.MemberConverter.convert
🥹
There
I'm saving that one
Also, if you just wanna convert a command arg to Member object you can simply typehint it to discord.Member (just saying)
Yea I sent the typehinting example from github earlier
yo would anyone mind helping me
i cant get my bot to import discord
or
from discord.ext import commands do that
Hi Guys!
!docs discord.py
No documentation found for the requested symbol.
!docs discord
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.
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?
If it works send it. Give it a try and if you get errors come back here
msg is undefined
And you should use checks instead, in case you don't want some commands to be limited
thanks, I realised and added the line that defines msg
By checks do you mean in each command I should add an if statement?
well, why don't you make a check instead
if you make a check you can use the restriction on specific commands for special case if you need
install discord.py

i have already done that
I'm a big noob, I don't understand checks 😦
restart vs code?
wont work i have already tested that many times
!d discord.ext.commands.check
@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").
show pip freeze
There's example there
on which python version is this installed and which python version are u using on vs code?
don't guess, check both cases
those 2 were the most common cases
no idea about this one, try asking at #python-discussion
!d discord.Colour.green
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`.
Use these factory methods
you can use hexcode if you want better green
show error
or the code if no error
can u paste it here and send 👇
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.
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
hex codes are 6-digits, you entered a 7-digit code here
my image for my embed thumbnail field is nvr loading?
any reason why this wld happen
you might have entered the url incorrectly
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
I just came back to d.py after 6month's of not touching it
what is discord.py views?
dpy has components, there's no need to install forks
!d discord.ui.Views containers for components
No documentation found for the requested symbol.
!d discord.ui.View
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.
idky i added s there lol
https://docs.nextcord.dev/en/stable/api.html#nextcord.PermissionOverwrite.update
to pass this through its like this right?
perms = discord.PermissionsOverwrite()
perms.update({"manage_members": True})
maybe, thats basically like dict.update so yeah
!d nextcord.PermissionOverwrite.update
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.
yes
you can do PermissionsOverwrite(manage_members=True) instead
yeah but i have them formatted from dict
didnt work it seems...
you gotta unpack the dict then
i dont get where it says A list of key/value pairs to bulk update with.
that updates it in your code, not at discord
ik but ill show error
what errror
Command raised an exception: TypeError: update() takes 1 positional argument but 2 were given
so its like, .update("manage_members", True)?
update takes **kwargs, not a dictionary
damn
no, update(**dictionary)
oh wait i literally can do that?
thought I still don't get why you'd use update
yes
you can instantiate PermissionsOverwrite and pass in the same arguments you would to update
see i was unsure about that so I just made sure
but thanks for clarifying 👍 will do that
will test now, thanks Lee
no problem
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
users aren't part of a guild and therefore don't have roles you can add
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:
you need a Member, not a user
oh ok, how?
Change the type hint to member
When the you don't know guild.get_role() exists 🦶
When the you
anyone have ideas for my bot im french but not needed just dm me
My grammar bad after ubuntu reinstallation
i installed my operating system with both the password and the confirmation password wrong and now im trapped
rip
why r my images not loading when put into a thumbnail embed?
just constantly to the loading thing
Is the url correct
Someone have script that can change discord name and icon with command?
does the url directly point to the file, or does it point to a web page that just displays the image? the latter wont render within embeds correctly (e.g. https://imgur.com/kRLELtr is a webpage while https://i.imgur.com/kRLELtr.png is the actual image)
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
yes
can you send the rest of your code?
@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?
and how can i start?
The suggested way would be to setup a logger using the logging module, but you could also just print() the error. It wouldn't give you much traceback to go off of though, unless you raise the error again.
where can i find out more about the logging module?
i was not clearly enough (sry) i mean dm them a custom message
these are the docs for the logging module
https://docs.python.org/3/library/logging.html
and there are some docs on how to use it with discord.py
https://discordpy.readthedocs.io/en/stable/logging.html
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
If you want to dm someone, you can use the send() method of their user/member object
!d discord.Member.send
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**.
Appreciate you
thank you am2i9
40/220 how can I calculate how much % the user has competed? like make it equal 18.18% (which is the %)
(40/220) * 100
You- multiple by 100... 
so take xp then divide by the max xp they need then times a 100 ok ok
thanks
yep, that's how you find a percentage
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
description should be able to
hmm, maybe you can't
it works in the footer?
im impressed about how i was able to type the same wrong password twice
me to 💀
webpage tht displays the image
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
cant do emojis in the footer.
lets go
yeah that's what I thought
but im trying to do emojis from other servers and stuff
is the bot in those servers?
no
then it can't use them
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
I've never seen that work tbh
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?
remove the a
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'?
message.message.content in your case
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
where do you guys store tasks?
the easiest way I can think of
@bot.command()
async def add(ctx, n1: int, n2: int):
ctx.send(f"Result: {n1 + n2}")
async def add(ctx, *numbers):
await ctx.send(f"Result: {sum([*map(int, numbers)])}")
i hope it works
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)}!")
or that yea
this + an on error would prob work a lot better
weird
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
!d str.isdigit
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.
How do I single the integer out in the line
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
thats what I did
this is bulletproof
Ah gotcha roger that
for character in string:
if character.isdigit() is False:
string.strip(character)
``` Something like this?
Actually that
I'm bad xD
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")
I think that should work
You couldn't just filter with isinstance then cast
I rarely use on_error so this might not work just post the error
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?
@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
...
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```
I know it sucks, but trust me it will save you pain later down the road
@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)
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
dont do that you'll fetch the same channel for every message
ur just gonna get rate limited
get_channel doesn't do api calls
I want to have the bot send multiple messages that are from other channel ids
doesnt?
it gets the channel from cache
fetch_channel does
cache
what if the channel isnt cached?
hold up so what do I fix 
it's just gonna return None
bruh ok ur way too smart
interesting nvm
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
eh, anything that's fetch_x is an api call, else it's probably cache
well yeah, cause whenever the bot sends the message to the channel, it'll trigger the event again
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
or just use a logger
^ you don't have to remove stuff, you have to add stuff
sqlite is a file-based database, so you have to be in the device that has the file to check the database
async def on_message(message):
channel = client.get_channel(1041527847396835338)
await channel.send("{message.content}")
if message.author == client.user:
return```
Still triggers multiple times I don't know if this is what you meant but.
@client.event
async def on_message(message):
if message.author != client.user:
channel = client.get_channel(1041527847396835338)
await channel.send("{message.content}")
you have to add that at the beginning, please try to at least understand what that check does
@slate swan what IDE do you use?
you use replit to edit your code?
yea? Im on a school chromebook 🥺
I see
its hard
wdym beginning
sqlite seems rlly easy actually
@slate swan
it is extremely easy. and I like to use peewee as my ORM. Just as easy
english?
ORMs are useful for translating class objects into database rows
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
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
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
wait what where do I put id
where do I put the id where the messages go
@slate swan i suggest you learn some stuff
its pretty obvious
message.channel.id == channnelid
message.channel.id == id
you replace channelid and id...
would anyone like to give me a bit of feedback on a project I've been working on?
I will
@fading marlin sure
would you mind a DM? I don't think I'm allowed to send it here
I don't mind
thank you! :)
Why does it keep doing this I added f and its an error 
where did you add the f?
You probably havent saved the codes new state and you dont even need it
(f"{message.content}")
f"{...}"
you don't need the f string either way
message.content returns a string
Oh okay, but how can I fix it so the bot doesn't send {message.content}
@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}") ```
remove the whole string, you don't need it. Just send message.content
It works just fine just only problem is {message.content}
so no ()
remove the string, keep message.content
what is it related to?
it's my take on a jsk-like extension
ohh I'd like to check it out
I don't know what you mean 😓. channel.send({message.content}) ??
is it the same as the one in ur bio?
yep :)
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
now you're not awaiting channel.send
also, message.channel.id == ... or message.channel.id == ... is unnecessary, you're checking the exact same condition
I did that cus I want to do more than one channel that the bot reads and sends to my channel
well zioqh helped with that
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
A set would be better
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`
do you have message content intent enabled?
the codebase is nice, documentations would be helpful
let me check
documentation as in a readthedocs/mkdcos/github wiki page
do you mean in my code?
@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
ah, thank you! I'll take a look into github wikis
dev portal and code
what exactly are you doing here?
yeah they're* great for static libraries that won't be edited much
ill also suggest mkdocs if you want more customisation
intents = discord.Intents.all() correct?
@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
I'll take a look into that too, ty
oh i never dumped them
this doesn't clear anything up :I
nvm doesn't work
probably why you should be using an sql database
"doesn't work" isn't really helpful. Any errors? What's occurring that shouldn't be?
if you're using json, then you can probably change it for sqlite
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
one sec
!pastebin
I have the correct intents enabled on developer page
Intents.default does not include message content
could I just add intents.message_content = True
yes
you have to define a variable that points to Intents.default before you call super().__init__
I don't understand
before ||(the line above)|| you call super().__init__, you have to define your intents and pass those into your constructor
I don't really know how to define the intents
create a new variable?
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
I'm really confused rn
I'm assuming you know how to make a new variable right?
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
I mean yes but I'm extremally confused
what are you using? dpy, nextcord?
Isn't boost bots against tos or am I tripping
before you call super().__init__, you have to make a variable. Do you know where you're calling that method?
not a boost bot its for twitch
print? All I can really think of.
or a value
intents I don't really know how to respond
!intents
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.
Lee do you know a way where the bot automatically adds @everyone infront of the message the bot gets from the channel ids?
just prepend @everyone to the message's content
how so?
I mean its not that easy
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) ```
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
@mighty pilot ?
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}")
It is that easy
@mighty pilot can yo u take a look at this
Yea one sec
please stop spoon feeding, it doesn't help anyone
alr thx
No promises I know what's up with it lol
hm?
sorry lol
i dont know when too much is too much
Did you mean to have an indent after the first line
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)
Can you use randint(3)? Like does that take one number?
Well rubyadd seems to be in a lot of things and it's value is ''
wait how can it be a integer then?
Wym
Is there any specific value that it's not doing?
Like does it show all the values in the level up embed
if random_chance is one then ruby add is a random integer from 1 to 3 which is then multiplied by your multiplier
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
so remove the else:?
No just indent the rubyadd line under else properly
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
Because you're sending 2 interaction.response messages
oh yea wait

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
@mighty pilot can u make the bot leave the guild?
do i need the guild id?
yea u copy what the docs say, please learn to read docs a little before this
That's what you told me to put though wym?
read it
?
i looked it up and didnt find it
read what
docs?
What is even happening 💀
idk I asked an question but uh uh
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
yea but this is different
people gotta start somewhere
i was told not to spoon feed him 💀
well you can help without spoonfeeding and without patronizing
it was your choice to give me the code I'm just asking if theres something I can look at
Because I want to add more ids
yea there is, where you see
or message.channel.id
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 💀
you can make a list like channellist = [123, 456, 789] if message.channel.id in channellist: do a thing
i think, there may be something im missing i havent done this myself yet
i need help w something tho rn
I was thinking of that
Are you gonna ask the question...?
How do i assign a unique url to each value in an embed?
yea was doing something
wait i think i got it
im making guild configs
like bad words, ect
"[Do you mean like this?](url_here)"?
Yes
But atm its assigning one url to all fields
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
Can you send the code for your embed?
link = cool link
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```
You've set the URL to https://google.com?{variantID} so it's just adding the same URL each time the for loop runs.
i want the same url but like the variantID bit too be diff
as have 10 variantids
Well what is variantID?
so want urls attatched to be like https://google.com?6712672, https://google.com?2182182
a like 9 long integer
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?
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
.
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.
Anyone?
At a glance, it looks like you're kicking the user before the bot attempts to DM them. You can't DM another user unless they're on your friends list or they share a guild with you and have DMs enabled. So try sending the DM before kicking them.
oh bruh im dumb
Happens to the best of us from time to time 
can you take a look at this @slate swan
I don't understand the question here, did the channellist work like that? Are you trying to do something else now?
Is the problem that your if interaction.guild.id != guildid: statement is running when you don't want it to?
yea i got it dw
Hi there can somebody point me in the right direction of a bot?
I need a discord bot with 2 functions;
- responds to all messages in #wallpapers with "⭐"
- responds to all messages in #wallpaper_requests with "✅" and "❌"
no its
str(interaction.guild.id)
you should read some documents