#discord-bots
1 messages · Page 86 of 1
what do you want it to do exactly
hold on lemme check the docs, there was something I remember
@faint sapphire
to make it stop searching after like 30 seconds
or to move on with code
maybe a while loop idk
oh shit the try except thing does work
thanks so much
its so weird that try except works for something that simply doesnt give an output
yeah if it's raising an error it'll work
since it's throwing an error try-except can work
apparently it does, wasnt obvious before cause output had nothing
yes you will get NotFound error if user with that id doesn't exists
Just use in?
they make a lot by selling nitros
unless the CCP keeps it alive in exchange for everyones info
they really dont
they only make ab 200 million
nowhere close for operational costs
Heya, anyone know why this is happening?
Here’s my error:
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/fun.py", line 46, in on_message_delete
del sman[message.channel.id]
KeyError: 957080091383463958
Here’s my code:
smc = {}
sman = {}
smad = {}
smaa = {}
rn = {}
stamp = {}
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = default.config()
@commands.Cog.listener()
async def on_message_delete(self, message):
if message.author.bot:
return
global smc
global sman
global smad
global smaa
global rn
global stamp
smc[message.channel.id] = message.content
sman[message.channel.id] = message.author.name
smad[message.channel.id] = message.author.discriminator
smaa[message.channel.id] = message.author.display_avatar.url
rn[message.channel.id] = datetime.now(timezone.utc)
stamp[message.channel.id] = discord.utils.utcnow()
await asyncio.sleep(3600)
del sman[message.channel.id]
del smc[message.channel.id]
del smad[message.channel.id]
del smaa[message.channel.id]
del rn[message.channel.id]
del stamp[message.channel.id]
@commands.command()
@commands.guild_only()
async def snipe(self, ctx):
channel = ctx.channel
try:
e = discord.Embed(color=0x2f3136)
e.title = f"Message from #{channel}, {discord.utils.format_dt(stamp[channel.id], style='R')}:"
e.description = f"{smc[channel.id]}"
e.timestamp = rn[channel.id]
e.set_footer(text=f"Message deleted: ")
e.set_author(name=f"Message author: {sman[channel.id]}#{smad[channel.id]}",icon_url = smaa[channel.id])
await ctx.send(embed=e)
except KeyError:
return await ctx.reply("I found nothing to snipe.")
yh, they rely on constant investments
i might be messing up the numb, cause it was from a vid i watched a year ago
!e
print(None or 1)
If the first value is falsy it goes for the second value
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
they generated more than $200 million in 2021 by nitros
its like netflix, theyre big but never were profitable
and might never be
!or @untold iron
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Thanks thats sick, where can i do a bunch of those commands without clogging chat up?
Hey, anyone?
#bot-commands
if i have a command that i want to have a "shared cooldown" how would i go abouts it? for example someone runs /poop and i want there to be 30s inbetween the next person who uses it?
Actually
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
There is an example
how to make a slash command cooldown ?
Anyone willing to show me a general setup for a python project?
Like repository setup, how you access SQL database, file setup etc
I'm finding myself making huge messes of multiple files / downloads trying to find a clean way to setup a project
You can take a look at how some oss projects on github are organized, like the Python bot
https://github.com/python-discord/bot
How is it deployed?
They run their services on a Kubernetes cluster hosted on Linode
I believe it gets deployed using a Github Action that deploys it to the cluster
probably much more complicated than you want or need actually
for python discord it's probably great
I see
How should I deploy a basic github project
So far I've just been running it off of my pi
But I find it very hard to test/run new code when it's hosted on the pi (I primarily code on my PC)
I would use SSH, but it's disabled on my college network
Also, which SQL database should I use? Don't want to pay for anything since it's a really small project, but I want to be able to work on the project from multiple computers, so a local database wouldn't work
the directory sman does not have that key, example
test = {"a":1,"b":2}
if you tried to test["c"] it would throw the same error because c doesnt exist in the directory. i didnt look at your code but you probably have a logic error somewhere
oracle iirc has free tier servers
you can have a db on there
Hey there i have created a simple command to create a new channel anytime the code !newtransaction is run, when that channel is created i want the async def newtestt function to run as soon as the channel is created, however i call that function on my channel creation command, when i call await channel.send(newtestt) i end up with this message in the new channel
Ahh, I see. How would I check if my key actually exists in my dictionary so I can delete it?
you are trying to delete something but you dont know if its actually there?
yeah
1s
try: # do this
del dict["key"]
except KeyError: # if the above code errors with the error "KeyError" do this
pass # pass keyword. litterally does nothing except end the indentation
thanks, i’ll look into it
my guess would be that you are not running newtestt, to run a function you need the brackets. rn you are just passing this function in as an argument and that is what comes out then
instead do
await.channel.send(newtestt())
if you have any arguments for it pass them accordingly
ty
ok i looked at your code for one second and you are trying to send from two different positions
either pass in the arguments like ctx into hte function and send it
or use return at the end of the function, returning the string to send into the channel
anyways, can anyone help me dynamically loading cogs from files?
Thank you, that got me closer
Error in terminal when running the command though discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: newtestt() missing 1 required positional argument: 'ctx'
I try pass ctx in the brackets
Prints this, not too sure why im very new to this sorry if its simple
newtestt() missing 1 required positional argument: 'ctx' this is the important part, i think you can figure it out yourself
how again do you call a function with arguments?
wait whaaskjndakjsd i thought i knew the error and just looked at your code lmao
I’ll explain one sec
😂 ??
or send the whole code, maybe then i could see the error
Sure thing
from discord.ext import commands
import discord
import token
import asyncio
from config import TOKEN
intents = discord.Intents.all()
client = commands.Bot(command_prefix = '!', help_command=None, intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is online')
async def newtestt(ctx):
NewchannelName = 'HAHAHA'
Newguild = ctx.guild
Newmbed = discord.Embed(
title = 'Test',
description = "{} has been successfully Tested.".format(NewchannelName)
)
await ctx.channel.send(embed=Newmbed)
@client.command()
async def newtransaction(ctx):
channelName = 'Transaction'
guild = ctx.guild
mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelName)
)
if ctx.author.guild_permissions.manage_channels:
channel = await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=mbed)
await channel.send(newtestt(ctx))
@client.command(name='delete')
async def delete_subcommand(ctx, channel: discord.TextChannel = None):
if not channel:
await ctx.send("You must provide a channel.")
return
await channel.delete()
await ctx.send(f"{channel} has been removed.")
@client.command()
async def botdm(ctx):
await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')
client.run(TOKEN)```
for bigger codes use
```py
<your code>
```
Tyvm
also the py for color codding because we all love colors
Ohh
i would remove this await channel.send(newtestt(ctx)) and instead newtestt(ctx)
else you are trying to send stuff multiple times
i think that might have been the error also, trying to call .send without a message because newtestt doesnt return anything
or replace it by await ctx.send(embed=newtestt(ctx)), and return the embed at the end of the function newtestt
Okay, so im a little lost, so is it that py await ctx.send(embed=newtestt(ctx)) doesnt have any link to the Newmbed in the function newtestt
Im not sure might be wrong
But then the part im confused on is how can i return the embed in the function? isnt it already embedded through ``` await ctx.channel.send(embed=Newmbed)
in the last line of the newtestt, instead of sending the embed, return the embed
Super sorry bro but how can i do that 😭
#Traceback (most recent call last):
2
E File "/home/user_712497713043734539/main.py", line 54, in <module>
3
6 decoded_data=f.text.encode().decode('utf-8-sig')
4
CAttributeError: '_io.TextIOWrapper' object has no attribute 'text'
This is made with nextcord a maintained fork of discord.oh
I will send code to helper
NewchannelName = 'HAHAHA'
Newguild = ctx.guild
Newmbed = discord.Embed(
title = 'Test',
description = "{} has been successfully Tested.".format(NewchannelName)
)
return Newmbed```
ye
Thank you
async def newtransaction(ctx):
channelName = 'Transaction'
guild = ctx.guild
mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelName)
)
if ctx.author.guild_permissions.manage_channels:
channel = await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=mbed)
await ctx.send(embed=newtestt)```
there is one thing you have to understand about python
EVERYTHING is an object
why are you sending two things
ohh one creator and one info what its for
Yeahh
Tried running discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'to_dict'
Can anyone help?
sure
line of the code where it happend? (send it)
don't steal my token🔫
REMOVE YOUR TOKEN??
Nah
do not under any circumstances send your token in here
not sure exactly where it is , here is the whole error `Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 39, in newtransaction
await ctx.send(embed=newtestt)
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\context.py", line 841, in send
return await super().send(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1520, in send
with handle_message_parameters(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 177, in handle_message_parameters
payload['embeds'] = [embed.to_dict()]
AttributeError: 'function' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wayed\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\wayed\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\wayed\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: 'function' object has no attribute 'to_dict'`
Assuming its the await ctx.send(embed=mbed)
line 39
Yep
again
you arent running the function
you are passing the function in as an argument
embed=newtestt(ctx)
and newtestt returns the embed
await ctx.send(embed=newtestt(ctx))
Sorry bro, im probably being mad stupid rn, ```@client.command()
async def newtransaction(ctx):
channelName = 'Transaction'
guild = ctx.guild
mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelName)
)
if ctx.author.guild_permissions.manage_channels:
channel = await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=mbed)
await ctx.send(embed=newtestt(ctx))
Still throws up an error when i run the command
`Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 40, in newtransaction
await ctx.send(embed=newtestt(ctx))
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\context.py", line 841, in send
return await super().send(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1520, in send
with handle_message_parameters(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 177, in handle_message_parameters
payload['embeds'] = [embed.to_dict()]
AttributeError: 'coroutine' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wayed\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\wayed\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\wayed\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: 'coroutine' object has no attribute 'to_dict'
C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'newtestt' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback`
Thank you for your patience
this is the part im confused on, the return from the function newtestt is supposed to be read, and then that is outputted in the embed=newtestt correct?
newtestt(ctx) becomes an embed when finished running thats how you can imagine it
RuntimeWarning: coroutine 'newtestt' was never awaited self._context.run(self._callback, *self._args)
newtestt is an async defined function, how does one call those?
also no worries i have plenty of time
yes
althought i am unsure if async enviroment is even needed in this case im not good with async
await ctx.send(embed=await newtestt(ctx))
Ahhhhhhhhhhhhhhh
Thank you very much it works, i see now its because new test is a async function
Ohhhhhhhhhhhh okayyy and i wasnt awaiting for the function only for embedding
Ok i fixed it!
Than you very much, im glad you made me think about it i learnt something new :))))) thanks alot dude
no prob
How do i make an async timer?
await asyncio.sleep(seconds)?
Hey there, im trying to add a reaction emoji that reacts to the new message printed in my new chat, however atm it reacts to the command
How am i able to tell it to target the new message printed in the new chat
heard that was bad for multiple timers going at the same time?
Would like it to be here
Not sure on that one
also that if the bot goes offline the timer is lost
If the script* goes offline
sure that
Ideally your script should never go offline
error stops the script from running?
I don't think so. You should have good error handling to deal with that
and what about if i intentionally stop the script for updating code?
That should all be handled dev side and flawlessly pushed via CI/CD
Extensions allow you to hot-reload without stopping the script as well
hm i see
how about using a loop and calling it from the db every, lets say 30 secs?
subtract the current time with the time saved in db? and if its in the negatives then call the funciton
You can sync it on startup
yea
solved! ```py
if ctx.author.guild_permissions.manage_channels:
channel = await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=mbed)
test = await channel.send(embed=await TransactionInitMsg(ctx))
await test.add_reaction(emoji)```
instead of using .format you could do this:
name=f"{channelName}"
Thanks, what is the difference or is it just faster to write?
easier to understand when you encounter a error and just looks better lol
and convenient ig
Theres no need to use f strings or format and the given example isnt correct.
Its a faster syntax sugar
huh?
how is there "no need to use f strings or format"?
Are you passing any static string or other values?
Or you could just add "Transaction" to it instead of using f strings or format
for n in nateamids:
await player.remove_roles(ctx.guild.get_role(n))
is there a better way of doing this? my goal was to: if the member had a role in a list (unknown role), get rid of that one in specific but the method i have now is removing all of them (32 roles) which is taking about 1 minute
hey
#imports
import os
import discord
import requests
import json
#intents import
from discord import Intents
intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
def get_quote():
response = requests.get('https://zenquotes.io/api/random')
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return quote
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$inspire'):
quote = get_quote()
await message.channel.send(quote)
my_secret = os.environ['TOKEN']
client.run(my_secret)
a simple code
which justs sends an inspirational quote from google
when i run it
shows this
Are you using replit?
ye
Yeah it's pretty common
it started to show this
Happens to most replit users, we tell them all the same thing
wht do u suggest then
VSCode and Pycharm are probably the ones I see the most
local?
if you're feeling adventurous, go for vim or emacs
hm
yes
no the thing is
cloudfare blocked MY acc
restricting the code to run
Hi!
when i tried the same from the other account, tis working perfect
Can I do game development with python?
Pygame? U can
Learn the pygame library
Hmm, is their a better module for gamedev? I wanna try something new.
You can use Pyglet
!pypi ursina
It's pretty nice though

Thanks, I will try pyglet and ursina,
happens sometimes ¯_(ツ)_/¯
Yup ig
It took you 2 mins smh
Guys. Cmds that allow for custom cmds and cmds that alllow you to create custom autoresponders make use of databases, right?
Guess everyone's asleep lol
fr
Yes
yes. In case of custom commands, they store the command name and the response to be sent upon invocation. Whenever your bot starts up, they make use of the add_command method of the Bot class (in case of discord.py or forks)
Btw, I've got a question I've been meanign to ask yesterday lol
yeah?
https://www.youtube.com/watch?v=xaWlS9HtWYw&list=PL-osiE80TeTsKOdPrKeSOp4rN3mza8VHN You think this would be a good idea to learn SQL? After I finish with this, will probably read that site you sent yesterday
In this video we will begin learning SQL Basics. To get started writing SQL, we need to first set up a server and a database. The server we will be using for these tutorials is Postgres. We'll walk through how to download, install, and setup PostgreSQL. Then we will create our first database so that we can begin writing SQL code. Let's get start...
Always find this guy helpful but idk if it's a good way to familiarize myself with databases
Plus, this doesn't seem to be a very long watch lol
yes it's okay if you wanna use that, reading just makes everything faster
Will go through this thoroughly lol. Will watch this then read that resource you sent yesterday. Alright. Thanks for the help
I got more error in replit for discord bot Help me
is there a limit to autocomplete?
Iirc it's 25
I can only help by recommending not to use replit
Why'd you even use it? Youtube tutorial or smth
nop none
that's for the options, that's the point if autocomplete
Forgot to say I resolved my issue, thank you anyway though!
import psutil smh
Install it
you can actually just send 25 autocomplete suggestions at a time :p
now since they are dynamic, you control which 25 of them to send on a particular response
I know lol
ofcourse
Fuc. I'm stumped. Need help:
@commands.command(name="nekoify")
async def Neko_ify(self, ctx, *, content):
Normal_Letters = ["L", "R"]
for Letters in content:
Nekoified_Txt = content.replace(f"{Letters}", "W")
await ctx.send(content=Nekoified_Txt)
Think of this as the owoify cmd.
When I use the cmd, it just sends the string with an additional letter "W" at the very last string letter. I assume that's because of the for loop ending at the last string?
What can I do for this? Brain's becoming dumber by every second lol
whats Letters? is that a list?
Oh, wait. I forgot. It's supposed to be Normal_Letters
It still sends the same result regardless though
yes, also beware that you can't check if list in str
Yeah, I tried kek
you need to check each element of list one by one
How can I do that?
Nice command 😳
if all(element in content for element in <list>)
``` should do
lol
this will check if all elements of the list are in content
damn. that's a lot of conditionals lol. Is that all that I need to do?
if thats your goal, yes!
ALright. Will first try understanding how that works. And Google is up lol. Thakns for the help!
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
this may help
Oh, didn't see that lol. Thanks again!
Yeah, this makes more sense lol.
import discord
from discord.ext import commands
client = discord.Client()
app = commands.Bot(command_prefix='-')
@app.event
async def on_ready():
print(f'{app.user.name}, Logged in.')
pass
@client.event
async def on_message(message):
await app.process_commands(message)
if message.content == 'hey':
print(f'{message.author.username} : called the function')
app.run('MTA..token..p7BTo')
The command doesn't working
I got no idea, anyone please help
No errors
I tried app(client).command tough-
Why did you create both discord.Client and discord.ext.commands.Bot instance?
tutorial1.intersection(tutorial2)
I saw someone on strackover put those together
shall i delete one of them?
You can only have one
Okay, i'll try that, thanks you.
import discord
from discord.ext import commands
app = commands.Bot(command_prefix='-')
@app.event
async def on_ready():
print(f'{app.user.name}, Logged in.')
pass
@app.event
async def on_message(message):
await app.process_commands(message)
if message.content == 'hey':
print(f'{message.author.username} : called the function')
app.run('MTAxOD..thesame...fnp7BTo')
STILL NOT WORKING-

Your bot have no message_content intent
message_content??? what is that tough-
Also, is this dpy 2?
I DUNNO
i found lots of hell tutorial on youtube
so I just following it
might help
I do read
import discord
from discord.ext import commands
app = commands.Bot(command_prefix='+')
@app.event
async def on_ready():
print(f'{app.user.name}, Logged in.')
@app.command()
async def solo(ctx):
await ctx.send("Hi")
app.run('MTA...thelatest.....mII86Fofnp7BTo')
yup, but, still not working
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
AYy
The code you found is outdated
Also yeah leave some spaces between functions (the right amount of spaces is 1 or 2 idr), your code will look better
Thanks YOU
YEAH-

noone can randomly guess the solution without looking at ur code
@slate swan
the error comes from "ticket category" command's checks
type this in your shell and then try running the code
what are you using to code your bot?
I prefer you try using visual code for now
write your code
go to shell or terminal, then typ the following
kill 1
and press enter
@slate swan r u making a bot for discord??
at what stage r u right now?
of making the bot
thats great
what are your bots current running functions? or u may say, commands
Just asking
I am also making a bot and facing some issues
thats why
damn thats great...
do you think u can help me out here with my bot?? 🙂 I'm also trying to make the same with addition to some embed msgs
Bruh.
Well, I'm not a pro at python but there's the error smh
Isn't that only for replit? For when your bot gets rate limited?
Hi
it fixed mine...same issue
Or I guess try this? Everything is worth a shot to learn something new
If it doesn't work, then yes. You probably need to fix some code errors. Check the errors in the terminal and figure out why it's happening.
how to make that little icon and title in embed
Like <icon> Dyno
in the image
You mean embed author?
not exactly the author
but tell me how to do that
embed.set_author.
it will be on the top?
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
^^^
Can anyone here help me out with my bot??
My bot seems running, bt he's not taking a command here, he's taking a few commands except the embed command. Anyone here please help me out 🙂 i can show you the code
Show the code
Hey @ebon mauve!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
use a pastebin
https://paste.pythondiscord.com
Just paste here @ebon mauve
I probably can't help since I'm also a newbie myself but there are lots who can here
Copy and paste all the File in the code there
hey, i dont want to use primary keys, but when theres a duplicate of something, is it possible to know + ignore the error and do nothing```py
sql = '''INSERT INTO mms(Server_ID, Server_Name, Server_Nickname, MM_ID, MM_Name, Invite_Code, Status) VALUES(?,?,?,?,?,?,?)
ON CONFLICT(Server_Nickname) IGNORE
how to use jsk in dpy 2
uh idk where to ask the question, but my debugger isn’t running correctly
Is there anymore traceback above that
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
here's my code, can anyone help me here??? it seems my bot is running but my bot ain't taking any command for embed options
on your embed where u say description= is spelt wrong
and just do await ctx.send(embed=embed) @ebon mauve
hey, how do i know if something isnt in a database
say i input a name which doesnt exist```py
try:
await cur.execute('''SELECT * FROM itemsInfo where name = ? ''', (items))
result = await cur.fetchone()
except:
result="None"
I think it will return None by default if there's no results
yh it prints none if i add print
i was confused cause returning None didnt work
yh i was tryna change the value of result if it was none, and that doesnt work
You can do something like
result = await cur.fetchone() or "Default value"
thanks
nothing happends
happens*
still cant use the command
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
I'd suggest you get the unexpired invites from the server and use them before creating more
Why are you creating both discord.Client and discord.ext.commands.Bot?
You can only have one
You must first get a channel from the guild and then create an invite with it
channel = guild.text_channels[0]
invite = await channel.create_invite(...)
^^^ you can take a look at the docs
And you have to be aware that every time you call that command, it will always create a new invite in the guild that it is in
👍
The first thing is that you did not define client. Second, what is .say?
If you want to respond to the command, you have to use ctx.send(mb)
im new and trying to make a bot and this pops up when i run the program:
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
and don't use Client really
what should i use
you can't make prefix commands using that
use commands.Bot
ok thanks
you can find guides in the channel's description ^^
ok thanks
async def on_message(message):
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
Big shoutout to @eternal fox he helped me out in my code's ❤️ love u bro
do you know what i can do for this

not slash commands lmao
you can refer to this -> https://gist.github.com/Ash-02014/426ec7974f705303a2363c739dd82309
it doesnt let me install discord.py
uh?
you already have it huh
don't install it smh
ok
I am new to python and i am trying to make an bot that moves user but it shows error from line 4 idk how to fix it!
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
TOKEN = "Secert"
@bot.command()
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
await member.move_to(channel)
print("move started")
@bot.event
async def on_ready():
print("Ready")
bot.run(TOKEN)
Error:
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'```
Please anyone could help?
nice what's it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
why does everybody have the same issue lmao
begginer 😐
[2022-09-17 12:19:24] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\PYBOT\main.py", line 10, in <module>
bot.run("token")
File "C:\Users\User\PycharmProjects\PYBOT\venv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
there are more errors i just cant send it all
show the whole error
!paste paste them here
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.
Hey @crimson compass!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
its too big
use the paste bin smh
Hey @crimson compass!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
channel_name=blah blah blah
Channels = guild.text_channels
print(Channels)
print(channel_name)
if channel_name in Channels:
return
``` i am getting Channels as an empty list
do you know?
enable the intents on ur bot dev page
oh alr thnx
@shrewd apex do you know broski
send the paste bin's link o_O
who broski?
same problem as me
You need to enable the intents feature from the discord developers tab.
enable intent
cant find them brat
It's in the Bot section.
if it works i love you guys
I LOVE YOU GUYS❤️
i did this and it gives me big fat error
code:
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"
@bot.command()
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
await member.move_to(channel)
print("move started")
@bot.event
async def on_ready():
print("Ready")
bot.run(TOKEN)
Same thing, read what i said above this message.
.
what i should do?
Go to discord.com/developers
okay
and hit the Bot tab, and from there enable all the settings under Privileged Gateway Intents
Nevermind, intents are enabled already
okay
and?
That is it, re-run your bot.
Okay everythin is okay but it doesn't move member from channel voice
it doesn't do the job
Then code wrong O-O
That is to do with your program.
channel_name=blah blah blah
Channels = guild.text_channels
print(Channels)
print(channel_name)
if channel_name in Channels:
return
i am getting Channels as an empty list
First, check if it's reading any channels, do
for _ in Channels:
print(_)
This should output all the channels.
tried, empty. So probably not reading ?
Yes.
and the fix is ?
could someone help me?
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"
@bot.command()
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
await member.move_to(channel)
print("move started")
@bot.event
async def on_ready():
print("Ready")
bot.run(TOKEN)
i program lua and i am new to discord.py i just wanted bot that just move members like this $move @rugged sigil channel voice....
please!!!!!!!!
Well, i'm not the best at discord.py, ask someone who is experienced i don't want to give help i'm not sure about.
enable guilds intents if already not done
its enabled
He has enabled all 3 intents.
I see
does the server have any text channels 💀
wait, where is the piece of code written
wdym
are you doing that inside a command
event
ic
@bot.event
async def on_raw_reaction_add(payload):
message = payload.message_id
emoji=payload.emoji.name
if message in Cache.Messages_to_Track and emoji=="📩":
user_discord_name = str(await bot.fetch_user(payload.user_id))
user=await bot.fetch_user(payload.user_id)
guild=await bot.fetch_guild(payload.guild_id)
channel_name=user_discord_name.replace('#','')
Channels = guild.text_channels
if channel_name in Channels:
return
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(channel_name,overwrites=overwrites)
embed = Embed(title="Form Filling",color=discord.Colour.purple(),description=f"bleh")
await channel.send(embed=embed)
entire code block
what does Channels print
[]
Intents = discord.Intents.all()
GUILD=[bleh]
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$"), intents=Intents)
o_O @slate swan
i want to make my bot to make a message embed without having to use a command
@client.event
i mean to like send a message and making it embed without having to type the embed command
could someone help me?
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"
@bot.command()
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
await member.move_to(channel)
print("move started")
@bot.event
async def on_ready():
print("Ready")
bot.run(TOKEN)
i program lua and i am new to discord.py i just wanted bot that just move members like this $move @rugged sigil channel voice....
**
please!!!!!!!!**
think what you are looking for is a slash command ?
@bot.command()
async def commands(ctx: commands.Context, text: str) -> None:
embed = discord.Embed(title="**Commands**", description=".embed \n.commands", colour=0x053305).set_thumbnail(url='https://cdn.discordapp.com/attachments/1020646324472926221/1020662000025608222/unknown.png')
await ctx.send(embed=embed)```
it works when i use it with .commands (and add text) but it doesn't work with just .commands
anyone?
what should i put
nah
it's len(bot.users) since it returns a list
text is required parameter, you can't invoke the command without it, you should assign a default value to text to invoke the command without providing something
such as?
text: Optional[str] = None
thank you
if no argument is provided when invoking the command then text will assume None as value
is pebblehost any good for hosting bots? what would y'all recommend?
my first call would be replit but i never hosted my bots online
I used to host my discord.js bot on repl.it before, used to go down occasionally, not a fan. It's hosted on heroku now but they are shutting down their free tier. Currently moving my .js implementation to .py.
I don't mind paying a bit to keep it running though. If y'all got any other suggestion/recommendation lemme know, thanks!
there's oracle's free tier
oracle hmmm
i myself use a rasberry pi 3b+ with ssh and ftp server installed to access files,
i develope a bot with my desktop pc with a token connected to a test bot and my rasberry pi always runs the actual bot with the code that was already uploaded. i heard you can do reloading on an event from file changed so automatic reloading can also be done
but it is around 40-50 bucks not sure rn
I see, I don't have a raspberry pi though but that sounds like a fun project
ha
hi bored im mom
hi mom im bored
there's a pinned message in the discord-bot-hosting thread that points to various virtual private servers you can pay for (lowest ive looked at is $5/month)
#965291480992321536 message
ooh thats sick thank you very much
can you show your code? id guess that you have (self, button, interaction) as your parameters, which need to be flipped around to (self, interaction, button) in dpy 2.0
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
await interaction.response.edit_message(content=f"This is an edited button response!")
@client.command()
async def button(ctx):
await ctx.send("This message has buttons!",view=Buttons())
yup
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):``` you need to switch `button` and `interaction` around
THANK YOU SO MUCH
why does it have to be in that order in the first place anyways?
originally during development it was (self, button, interaction), but then they changed it to (self, interaction, button) for the final release for "consistency" i think they said
Thats the order the library internally passes arguments upon an pressing a button
ah it was one of danny's commits
https://github.com/Rapptz/discord.py/commit/968a1f366fa1913c621bc866aedde068b86e9654
This is more consistent with the rest of the library which always has
the interaction as the first parameter. This has been done before in
the command extension as well, the first parameter is always either
self or the context.
hmm
Anyone know how i can setup source control with my project, nothing large scale crazy just a simple commit and ability to revert. All the tutorials on youtube seem crazy complex?
um....this isn't the right channel really
My bad, which channel should i ask in?
it's easy though, you can read the official github docs -> https://docs.github.com/en/codespaces/developing-in-codespaces/using-source-control-in-your-codespace
git is quite popular, if you run into issues. make sure to search up the internet, you'll find solutions easily
you get a perpetually free 1.5GB 2 core VM here
how did you generate the link
A small calculator that generates Discord OAuth invite links
.
try going through the discord developer website
go to your bot application
on the left, oauth > url generator
select bot, then choose permissions you want
that'll spit out a link that you can use to add your bot to servers
async def ip(ctx: commands.Context, text: str = None) -> None:
AttributeError: 'Command' object has no attribute 'Context'```
did you name a variable the same as the module?
@dusk girderI can't use google transate, sorry for my english, I can't get any interaction when I click on the following sections, what should I do?
you able to show me what you see?
anyone
@crimson compass
assuming commands is a module, that is
yeah
yeah try naming the variable something else, or doing import commands as <alias>
Guys how can I send dm to user thought discord v8 api?
Sorry for the late reply
you use raw requests?
You mean post request?
yes
select bot and applications.commands
select bot in the large area above
not application.commands, bot
then choose permissions you want the bot to have on your server
I believe most of the people here do not use raw requests, you can ask at discord developers server if you get any doubt.
here's how you can create DMs - https://discord.com/developers/docs/resources/user#create-dm
by the way, v8 is deprecated
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
I am not able to understand how to pass the message
(bot is here btw)
you get it to work?
also I never had to select applications.commands and it worked fine
with that, you create a dm channel
and then you can send msg to that channel
it is only for application commands in case they have any
application commands like /command or am I misunderstanding?
slash commands and context menu commands
both of them together are called as application commands
context menu??
never heard of that one before, I'll have to try them lol
also by just selecting "bot" I can still use slash commands so idk lmao
how do i make my bot delete the command ive typed
ex. i type hello and it replies with hi and it deletes the hello
presumably await msg.delete()
these
yeah I'm definitely trying these when I get home that's cool
do i put it like this?
@bot.command()
async def embed(ctx: commands.Context, *, text: str) -> None:
embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(url=ctx.author.display_avatar.url)
await msg.delete()
await ctx.send(embed=embed)
no
how
oh so that's a context not a message I seee
yeah
idk what attributes the context class contains
ctx.message
how do i check a user for permissions using interation
and do i put it where i put await msg.delete()
just the classic way I guess
I'd put it after personally but I don't think it matters
after the ctx.send*
it doesnt delete it
idk then lmao
show the code
@bot.command()
async def embed(ctx: commands.Context, *, text: str) -> None:
embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(url=ctx.author.display_avatar.url)
await ctx.send(embed=embed)
ctx.message.delete```
await ctx.message.delete()
You need to await it
thanks
also they actually needed to call the function lmao
🥴
How could i get the last 2 messages of a channel?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
the limit and oldest_first kwargs should help
Remove the *
Did that
renamed message to number because well i already use message. But number.content just returns whitespace
send full code snippet
Entire command yeah
Command?
I didn't write most of this as this is a custom fork of a bot
Also this was before /commands
Replace channel object with channel = message.channel
this one?
so this should work?
Yeah it should
Nope just whitespace again
Maybe the oldest messages had some weird formats
set limit to 20 and maybe smth changes
Shouldn't since i just sent a normal message
Nope. everything whitespace
Does that part of the code get executed for sure? add print('test') above print(number.content)
Considering the fact it's printing 20 lines of whitespace...
Oh, welp
what does number.author return?
It works
Printing just the message it throws out all the data and stuff but i see no content
Send a picture of these messages xd
Might be a bit hard cause they go off screen
From Discord text channel
<Message id=984508464548167701 channel=<TextChannel id=984502146185691157 name='counting-test' position=11 nsfw=False news=False category_id=474783551326519319> type=<MessageType.default: 0> author=<Member id=236195385415172106 name='DangerMage' discriminator='1696' bot=False nick=None guild=<Guild id=474783551326519317 name='MY MUSIC' shard_id=0 chunked=True member_count=7>> flags=<MessageFlags value=0>>
oh
Did you enable the message_content intent
message_content intent?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
goddamn intents, I usually enable them without thinking xD
How do i enable it?
It's a kind of a good habit in my opinion 
By enabling it
intents = discord.Intents.default()
intents.message_content = True
Do i need to do that inside my class or outside my class?
And make sure to enable it in dev portal also
discord.py - how to make a bot work only when you have a role?
Ah yeah that might help
Make the bot check user role and then go on from there
Do i need to reinvite it now?
nah
Nah
Thought Discord bots had cool features, until saw Telegram ones xd
WOOO
🫠
Now to compare them and make a counting game >:D
or you can just do:
if role_id in [role.id for role in ctx.author.roles]:
...
convert content to integer
You also need to call the number.delete coro
- translation -
delete->delete()
Oh
()?
Bruh
I bruhed
Just give it a go xd
It's uh. deleting the number before the 2...
And doesn't delete the message if it isn't a digit
Are you trying to make counting game
Yes
You just gotta fetch the last number on bot startup and save it, then compare it to the new messages and update it
History method is easily breakable
I have no idea where in this fork i would add that
found it
probably want to do it here
How can i pass the number between the 2 classes between the 2 files?
Depends in what context
well i found the startup file or at least a spot close enough where i think it would be safe to retrieve the last number but it's in a different class in a different file
did u get it to work?
No
It's doing stuff wrongly
I made it delete words now but it still deletes numbers
if message.channel.id == 1020721733407359089:
messages = await message.channel.history(limit=2).flatten()
if not message.content.isdigit() or not int(messages[1].content) + 1 == int(message.content):
await message.delete()
``` Just created that, it should work
This person said history is easily breakable though
And can't bots not get history if the message is too old?
Why do you want to fetch the oldest message? :D
Not the oldest one but the counting game channel we have goes inactive every now and then
When there's a lot of ppl spamming yeah
But yeah his method is better ig
Mhm, but if 15-20 ppl enter a number at the exact same time, then it might become a problem
hmm
Isn't his method breakable at that point as well?
well. i guess just check if the message is a digit then compare to the stored number would work if it does it for every message
mhm
But i'm not sure how to do this
Also Your method doesn't work cause .flatten() isn't an attribute apparently
just doesn't work in general
how to whitelist people to use my bot
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Good bot
No idea how to do this stuff so i'm gonna go eat
so how would i do it with docker?
!src
check out our bots repo to see how we do it
I have a server that has been around for a week and a server that has been around for a year. Both are community servers. However only the one that has been here for a year can make a forum channel. Is there some sort of server age limit to make forum channels?
I tried to make the forum with my bot but I got this error
Traceback (most recent call last):
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\features\python.py", line 156, in jsk_python
async for send, result in AsyncSender(executor): # type: ignore
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\functools.py", line 125, in _internal
value = await base.asend(self.send_value)
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\repl\compilation.py", line 154, in traverse
async for send, result in AsyncSender(func_g(*self.args)): # type: ignore
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\functools.py", line 125, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 1, in _repl_coroutine
await _ctx.guild.create_forum('Homework Help')
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\discord\guild.py", line 1634, in create_forum
data = await self._create_channel(
File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50024): Cannot execute action on this channel type
did you try to create the forum channel in the server that did not have the forum channel feature?
Yes
I’m basically wondering what I need to be able to make forum channels
you need to enable and actually have possibility to create that channels
the server must have the following things:
Community
250+ members
user locale en-GB
however forum channels should have arrived at almost all servers, which means that soon it should also arrive in your server, these requirements are no longer met (only the community feature is required)
I’ve already got them in my server with 1 user (me) and 10 bots
Thank you for the responses!
10 bots with one user...
I assume that older servers are getting them first
Got code?
those restrictions were valid when the forum channels were still in beta
oops wrong message
they are looking so close
how can i put them further
embed=discord.Embed(title=f"{message.author.name}'s stats", description=f"Started journey on {zaman}", color=0xffa3d9)
embed.add_field(name=f"Made {data[id]['stats']['max money']} in total", value=f"Lost {data[id]['stats']['losted money']} in total", inline=True)
embed.add_field(name=f"Boguht {data[id]['stats']['cnsbought']} coins", value=f"Sold {data[id]['stats']['cnssold']} Coins", inline=True)
embed.add_field(name=f"Gambled {data[id]['stats']['gamble']} times", value=f"Won {data[id]['stats']['sccsgamble']} of them", inline=True)
embed.add_field(name=f"Worked {data[id]['stats']['work']} times", value=f"Answered {data[id]['stats']['sccswork']} of them correct", inline=True)
embed.add_field(name=f"Wrote a sentence has 'hbc' on it {data[id]['stats']['hbc']} times", value=f"And make ${data[id]['stats']['hbcgain']} from that", inline=True)
embed.set_footer(text="If you think something is wrong, contact with us!")
await message.channel.send(embed=embed)```
thats the embed
you don't control them, discord does ;-;
!voiceverify
Or, you could display your text in a different way, like just putting it in the description with markdown
**Hello:** World
**Statistic:** $1000000000
**Meaning of Life:**: 42
maybe you could play with some invisible char
wdym
I feel like that would screw up some stuff, especially on mobile
is it chr(173)?
Looks fine to me. That’s about as spaced you’re going to get fields.
maybe add some Emojis 🦆
You got a typo in the embed
Also consider spicing things up with ASNI Code-blocks (if you don't care about mobile rendering)
uhm would anyone have some code for me that reloads cogs because im lazy?
asking for a friend
actually faster than making a ping command
How do i retrieve the message authors username in Hikari lightbulb?
how do i make a commands.cooldown for slash bot ?
i dont have a pro answer
but better than nothing ig, i think using a database could work, where u store the last time the user used to command
or u make an async coroutine
what is a "ping command"
im jokin
is there an easy way like this ```
@commands.cooldown(1, 7200, commands.BucketType.user)```
idk im not an expert
k
those two ideas are the best i can make up
yo
my question is quite basic :/
but im in a hurry to make all the commands functioning again
for a specific channel, i want the bot to read all the messages
i used to use message.content, i now moved to bot commands and dont know if i use message.context or something like @bot.listen
!d discord.ext.commands.Context is always the first argument of a command
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
Check its attributes
thanks
i found it @app_commands.checks.cooldown(1, 7200, key=lambda i: (i.user.id))
wow
Oh heck dpy even uses different submodule for app commands decos 💀
can u share the link where u found that pls
i wonder if it applies for non slash commands too
whats that pfp
non slash things is smth else ill show you
for non slash command@commands.cooldown(1, 86400, commands.BucketType.user)
awesome thanks
np
awkward attempt at getting a full message's content 😵💫 sorry im rushing things today```py
@bot.command(case_insensitive=True)
async def filterMessage(ctx):
if ctx.channel.id in hightierschannels:
fullMessage = ctx.message.content
hi
how do i make smth like this @commands.is_owner() in slash commands ?
what library
idk i just use lists containing admin ids
it can also be stored in a database
but then i rely on adding admins through commands rather than roles
i prefer that anyway
not a good idea if u making a public bot tho
ye
i have not implemented any security features yet
litterally everyone could execute litterally every command
not good
ahh nobody knows the commands its only like 5 commands
im still working on structure, speaking of which can anyone tell me the event name for when the bot joins a new server?
nvm i put adding new folders for server data in my read data function
yh before adding lists of admins i had some commands with weird names so no one discovers them lol
yo i cant figure out how to see the full message content without having a command name :/```py
@bot.command(case_insensitive=True)
async def filterMessage(ctx):
if ctx.channel.id in hightierschannels:
fullMessage = ctx.message.content
how do you manage files? i just wonder if there is a better way then how i am doing it
"".split?
files?
to store data about users or servers
use a database like aiosqlite
ull have to, for each ppl to save their command prefix or whatever
its an async sqlite
if you know there is going to be a space in the input command you can use "".split(" "), and then use only the second object of the tuple
or use *args
async def echo(self, ctx, *args):
string = ""
for part in args:
string += part
string += " "
await ctx.send(string)
this is my echo function
thats online right
ahha i never worked with sql lmao
so it can do more things at the same time
rn i have alot of text files each with their own value stored inside of them, and a decorator to get a dict out of it, and afterwards it writes changed information back to the files
also i just started having this really annoying typo, i write os.listdir as os.listidr
happend like 5 times, even when i wrote the first os.listird ASLDMLAKSDMÖLASMDLKASMD I CANT
sounds complicated
ehh its not that hard 1s let me get my script
def server_data(func):
"""
Decorator to get/write guild data when executing a command
"""
def inner(self, ctx):
# If guild has no directory yet, create one
if not os.path.isdir(f"./data/guilds/{ctx.message.guild.id}")
os.mkdir(f"./data/guilds/{ctx.message.guild.id}")
# Reads the preset for new guilds and so on
presetDict = {}
for entry in os.listdir(f"./data/guilds/preset"):
with open(f"./data/guilds/preset/{entry}", "r") as f:
presetDict[entry] = f.read()
# Reads the data from the guild the message was send from
guildDict = {}
for entry in os.listdir(f"./data/guilds/{ctx.message.guild.id}"):
with open(f"./data/guilds/{ctx.message.guild.id}/{entry}", "r") as f:
guildDict[entry] = f.read()
# Checks if guild data is in sync with preset, if not, sync
for presetKey in presetDict:
try:
guildDict[presetKey]
except KeyError:
guildDict[presetKey] = presetDict[presetKey]
newGuildDict = func(ctx, guildDict)
# Finds the difference between the old (guildDict) and new (newGuildDict) guildDict
for guildKey in guildDict:
if newGuildDict[guildKey] != guildDict[guildKey]:
# Changes the values in the files if there is a difference
with open(f"./data/guilds/{ctx.message.guild.id}/{guildKey}", "w") as f:
f.write(newGuildDict[guildKey])
return inner
anything using this decorator returns the edited (or also unedited) data
ima change it tho to get a tuple so i might be able to have multiple returns not sure if i might need that
idrk what im looking at
but use https://aiosqlite
but then i have to learn new stuff asnasdkn
that is not how links work
dw ill use google
it looks good but i dont see why i shouldnt use my current script
should i start coding with pycord or discord.py
damn i didnt even know pycord existed
user id was ctx.author.id right?
Hey there, im learning how to code a discord bot, however the problem i have is i never know what features there are i can use. e.g. what other reaction events can i do aside from on_reaction_add e.g. is there on_reaction_remove ect
Is there any list or so where i can search up these and find more
discord.py documentation events would be my guess
Ty will check it out
!d discord.on_reaction_remove
discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").
This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Note
Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
which discord.py version is the best to use for bot coding
That one
ok ty
how do i make my command not run if the user doesnt have a specific role/specific permission??
you cant use self outside off class functions where you gave it in as an argument
remove the three lines after the __init__ function
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
And has_permissions for permissions iirc
thank you
if i mention someone inside of a message which gets reacted to, how can i get the id of who was mentioned?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
so in on_reaction_add you should be able to use reaction.message.mentions
cant understand
1s
done still not workinf
ty
explain
Explain what
If you need a guide on classes, check Corey Schafer's series on OOP on youtube
ohk k
class foo:
def __init__(self):
self.length = 1 # can use self here because it is an argument
# cant use self here because its not an argument BUT we are in the self scope so you can set a self variable like this
length = 1
im not even sure if scope is the right word
also if the user doesnt have permission to use the command how to i make the bot send a message that the user doesnt have the permission required
are you using discord.Client or discord.ext.commands.Bot?
the 2nd
let me get the docs for you
there is a commands.check, if you are using cogs, or a bot.check decorator which takes in a function to run and test various things
thank you
!embed
#bot-commands
@bot.command()
@commands.has_permissions(administrator=True)
async def embed(ctx: commands.Context, *, text: str) -> None:
embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(
url=ctx.author.display_avatar.url)
await ctx.send(embed=embed)
await ctx.message.delete()
@bot.command()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You do not have {commands.MissingPermissions.missing_perms} to run this command.")
it doesnt work
can anyone help
Decorator for on_command_rrror should be bot.listen() or bot.event
yall i made a antinuke w a usual 0.33-0.5 reaction
What?
yk what a antinuke is
Yes? Wdym by 0.33-0.5 reaction?
Cog.listener()
async def on_guild_channel_create(channel)
start = time.time()
#do something
end = time.time()
print(end - start)```
check if the user is whitelisted?
Thats nice, an auto banner that bans you when making a guild channel kek
but if ur not whitelisted it bans u kek
Why would you use a whitelist?
trusted members..
other bots like Defender, summrs, are basically the same thing as mine 💀
The logic is quite funny imo
Ok
even if the member is trusted you cant measure the time of your bots reaction, just an average which you never said it was an average and where do these users get stored?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
And i wonder if automod will get new features like an antinuke which i wouldnt doubt that it wont come in the future
this probably causes more confusion than it clears
class foo:
def __init__(self):
self.length = 1 # "self" represents the new instance of "foo" that was created.
# self cannot be used here, you are creating a class, there is no "foo" class (it's being created) or instance of "foo" yet.
length = 1 # this assigns "length" as a property to the "foo" class. this means foo.length is 1.
thats the point no im just really bad at explaining, ty
This causes even more confusion
All of it
you can elaborate
self doesnt always represent a newly created instance, should explain it.
"self" represents the new instance of "foo" that was created.
I would use the word declaring and not creating as it may cause confusion, foo can be created inside of itself so there can be a foo inside of itself
self cannot be used here, you are creating a class, there is no "foo" class (it's being created) or instance of "foo" yet.
i'm pretty sure its not a property but a class variable
length = 1 # this assigns "length" as a property to the "foo" class. this means foo.length is 1.
selfdoesnt always represent a newly created instance, should explain it.
Given the__init__()method, that's inferred. I don't think__init__()would be used if a constructor wasn't intended.
I would use the word declaring and not creating as it may cause confusion,
foocan be created inside of itself so there can be afooinside of itself
Niche scenario, but valid point.
i'm pretty sure its not a property but a class variable
Sure, I could have worded that better. But "property" is just a broad term that also covers class variables. Please excuse my JavaScript exposure lol
Traceback (most recent call last):
File "main.py", line 5, in <module>
discord.ext.commands (command_prefix = "/")
TypeError: 'module' object is not callable
anybody know what i need to fix?
Should explain it as "in this case", __init__ isnt a class constructor either, Well in python a property and a variable thats bound to a class dont behave the same.
There's some terminology being used incorrectly. What do you define as a class constructor? __init__() is exactly that. Also saying "a variable bound to a class" is very confusing, it's not a variable.
While technically it's a variable, it's just not usually referred to as one.
__init__ doesnt construct anything hence why i disagree
That whole point is confusing, "its a variable but not called a variable"
Convention, we don't call properties/attributes variables
__init__ is 100% a constructor
It constructs the state of the class, basically 100% of the class
Its annotation is literally ClassVar
Would disagree, it initiates the class's attributes but doesnt really construct it over something like __new__
It's inferred as a class property
You said __init__ doesn't construct anything though?
It constructs the state
Otherwise you'd have a global state using only class attributes

43,615
311,924