#discord-bots
1 messages Β· Page 37 of 1
noo disnake and pycord(
yea? it wouldn't help very much though, try print the label or something of the button which will help you locate the problem
any tips on how can I get the grip of hikari
yea its hard to find things out
you can check this for a quick start
https://gist.github.com/sarthhh/6377b5047a0a3055bc08208406fc35fe
*nextcord
thnks man
what is REST API?
Not a great place to ask such a broad question, would take too long to explain
Best way to start is legitimately to Google "how to make a discord bot"
I disagree that would bring up lucas tutorials
I started with bad tutorials, gotta start somewhere
starting with bad tutorials makes things harder in the long run
better to start with python fundamentals and then the documentation
Where are the good starter tutorials though
The problem with starting with python fundamentals is that it saps your motivation, I would debate that it's better to jump in and actually see that you can make something badly
For python basics, Automate the Boring Stuff, PY4E are great
being stuck on an issue for weeks because you don't have the prerequisite knowledge to solve it is even more demotivating
its like a Client Server data exchange medium, the client makes request to a server using GET, POST and PATCH etc methods and the Server processes it
discord.py'a REST api stuff is undocumented inside http.py in case you're wondering
await view.on_timeout() then?
Or is it
. . .
you need to override on_timeout method of view class if you wanna do something when the view timeouts
mhm
My connection is good not bad
class Myview(View):
async def on_timeout(self):
# stuff
Replit con is bad as hell
Hmmmm
Any way to fix?
A good processor for fast opus encoding
Get a VPS
how will it get the view which I want ?
I dint have π°
print(self.bombs)
print(self.pos)
print(self.is_bomb)
print(self.bombs_around)
self.label = str(self.bombs_around)
print(self.label)``` now im confused even more... @paper sluice
All those are blocked in Russia tho screw them
hehe)
Do digital ocean provide free vps?
Or Google
Idk how to host bot
I have samovar server
you can get 200$ of digital ocean creds with github student developer pack
Yeah but they give you 100$ for 2 months and that's all
you need a credit card for any free vps you want to use
My school not gave me email ;-;
I have guides, check my gists on github
@slate swan
Google doesn't support individuals in some countries and they work similar to digital ocean although I don't know certainly
Guide is very confusing
Which one exactly, I have 2
There is one only
https://gist.github.com/67fe2018d85abcf9c21541821ff2ef37
https://gist.github.com/Exenifix/a8aa68a4976389757ff3121e6daadcf6
Possible to respond to an interaction which was sent and then bot turned off, then the bot would still respond to it
For now
If we send buttons with a message and turn off the bot and then turn it back on again it wonβt respond to that interaction
!d discord.ext.commands.Bot.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
Thanks
Um what?
So if I just do
view.add_item(something)
await ctx.send(content=βsomethingβ, view=view)
The bot will respond to that button even when it is turned on and off?
Have someone tried to automate TikTok uploading? I see some already done Python bots on that, but they require that you login manually, which destroys 90% of the purpose of automatic upload.
This channel is for discord bots specifically, you may want to claim a help channel for this: #βο½how-to-get-help
Is there any on_button_click or on_interaction event?
Which library are you using and what are you trying to do?
discord.py 2.0
Iβm trying to respond to a button which was sent before the bot turned off
You can just make a persistent view
just for example
If you turn the bot off after sending a button
And then turn it back on it wonβt send the response to that button sent last time
how?
My discord π
It was on for many hours smh
21 π
Did what they said in the docs but the interaction fails when I turn the bot off and on again
@vocal snow ^
Hello, its showing for me that there is /ping slash command but actually thats not true, its also showing in the menu when i type /, how i can disable that? may someone help me please?
No and yes
Make sure youβre use add_view for persistent buttons
Psst off
Guys anyone give any command idea for my bot
A command to... make new commands
command to change commands
Give any useful idea
how is my idea not usefulπ
Who would use that ;-; (sorry if my message hurt you )
Is it better to move on to nextcord from discord.py?
Hard to make
practice
no
absolutely no reason to
Dpy better
Idk, nextcord is a fork taken from discord.py
still no reason to
And since discord.py is discontinued....
No
it isn't
Well ok ig
Bruh it is π
π
it's been being improved again
Oh
for more than half a year
Is ghost making 2.0 version then
Ok then
man you're late, missed much
π
Haven't been doing this stuff for almost a year, came back last week and saw his message
pip<python version> install -U git+https://github.com/Rapptz/discord.py
python version part optional
just put it there for people who can't put the right pip on path
How can I make a comand that can run js in discord.py?
Ayo what π
uhmmm, I am not sure what you mean, but you can run cmd commands with os.system, so just do os.system("node index.js") (just replace it with whatever command you want)
Can somone help /
i put the id right ?
new to this and and confused
You are missing one parameter while calling the function
I think you should mention role
Is it a moderation command? If yes then you can just use @commands.has_permission(permission name=True)
yh its a gban command
Imagine not spending money for hosting and buying AirPods Pro π
@commands.has_role(βAdminβ)
I assume you mean global ban from gban
@commands.has_permission(ban_members=True)
got it
yh
Did you check application_commands when adding the bot to the server?
define it then
from discord import app_commands
why syncing in on_ready, that's so horrible
make a command for syncing π
"works" does not define good, use a setup_hook, a better example to yours, no offence, is -> https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#slash-command-application-with-a-client
hmm sometimes on setup hook u may get sync called before on_ready error something similar i got that once then i switched to sync with commands
that's literally not a thing
wait a sec
waiting
i swear i got it lemme try to replicate
I didn't know about setup_hook before, a guy suggested it once, but since my code worked I was to lazy to change it, thanks for the advice tho, gonna keep the link ready just incase
Hey, i try to create an command for a todo list. I have a txt file with some words. When I enter the command and a word the discord bot should delete the word from the txt file. ```py
@bot.command()
async def v(ctx, arg):
words= open("user.txt", "r")
if arg in words:
print("Check")
for line in words:
if arg in line:
line = line.replace(arg,"")
words.write(line)
words.close()
the txt file:
```txt
test
123
ping
But the bot dont delete the word
the gist is in the pins
second from the top
dont use a txt file first of all
also read the file after opening it
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.read(f)
Like that?
!d json.load
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).
*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
smh read the docs
Okay but how can i check if the word is in the file and can delete the word from the file?
if "word" in data:
data.pop("word")
write_to_file(data, file)
nice
raise Missing applicationID
discord.app_commands, errors. MissingApplicationid: Client does not have an application id set. Either the function was called before on ready was called or application id was not passed to the Client constructor.
2.0 publishing soonβ’οΈ
nice
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)
``` so?
but they make embeds unhashable for eq idk y
Wym
Never really had time to get into programming since a few months now
I am missing out all the new stuff that's been happening
mean embed object cannot be used as dict key and added in a set
@bot.listen()
async def on_member_join(member):
channel = get_channel(bot.get_all_channels(), 'ππππππ βππ')
background = Editor("bg.jpg")
profile_image = await load_image_async(str(member.avatar_url))
profile= Editor(profile_image).resize((150, 150)).circle_image()
lol = Font.poppins(size=50, variant="bold")
hit = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325,90),150, 150, outline="white",stroke_width=5)
background.text((400, 260), "Welcome to Nebula", color="white", font=lol, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=hit, align="center")
file = File(fp=background.image_bytes, filename="welcome.jpg")
await channel.send(f"**Hello** {member.mention}! **Welcome to Nebula**. **Pls check out** #πΆπππππ π **for guidance. Get some fancy roles from** #ππππ-π
ππππ . **Introduce yourself in** #πΌππ‘ππππ’ππ‘ππππ **and have fun.**")
await channel.send(file=file)```
bummer i was doing it for paginator
Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)
i changed the bg.jpg and i am getting this error
and instead of the they added __eq__
pls help
What is even the use of __eq__ in embeds
Why u even wanna compare embeds
why u ask me idk go ask danny πΏ
anyone π₯²
Mind sharing the code for that dunder? My, uhhh, net is a little.... fucked rn
what u gonna compare to embeds for in first place i have no idea
example they didn't give any example
Lemme see the code and check what they even comparing
bruh ;-;
no file with the name bg.jpg
i have it
basically implement eq mean they want us to compare like discord.Embed() == discord.Embed()
Nice
it was working earlier tho
os.listdir()
Print this
Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)
But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```
Json file:```json
[
"test"
]
Wait, @shrewd apex if they made it unhashable, that means u won't be able to use it as a list element anymore, right?
list doesn't hash
Hm, I am mistaken then
what's this Editor is it like some 3rd party lib of pil
from which lib is this?
Nice __eq__
easy_pil
yeah they made dunder for == as i said
huh pil is easy what's this easy_pil now might as well just use pil
Lmao
any benefits?
dk bruh, i followed a vid
Lucas?
and it has been working for a while now
civo ig
Nvm
ok pil gonna go major updates soon u might want to switch as well
What updates?
ight i will try ig
I'm now completely confused because, I added letters to every field possible but it still says the same error
idk if this easy pil gonna keep
quite a few along with 3.11 they deprecating prev Image filters gonna add something like Resampling next year around
O
pil and pillow are different right?
my hunch either the roles or permlist empty
iirc pillow is a continued fork of pil
ight thx man
it's pillow now
β
how can i add author in embed = discord.Embed
not vai embed.add_author\
How do I fix this?
I get that yeah
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
``` for all 3?
Yes, its the roles; if someone has no roles its basically empty thats why, but how can i check if the user has any roles? And if not, send a other embed?
@client.command()
async def load(ctx, extension):
await client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
await client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await client.load_extension(f'cogs.{filename[:-3]}')
``` my bot doesn't respond to anything lol or am I doing something wrong
U never send anything
u never do await ctx.send() or smth, so u never get a response
thats not all my code
just the things in my cogs etc
It just doesn't respond to my cogs
Nor my main file
wym doesn't respond bro
I just do do the command .ping for example but the bot gives no response nor error in the console
Can u print bot.commands?
and see if all the commands are there
also show yr error handler
the for block must be unindented
as it is now your cogs will only be loaded by running the command unload
I indented it, because of this
how can i check if a user has at least one role?
Like if the member has at least one or more roles DM him but; if the member has No roles send a message into the chat?
you don't need await
if ctx.author is ctx.guild.owner:
i think
Since 2.0, u need to await
I use 2.0 yes
he's using 2.0?
Why not?
skill issue
Yah
nonono that discord being discord issue it worked fine in another bot now mess up on a sample bot
There's no downside, it's good to be stay up-to-date
Yeah
yes
skill issue
π
rip i cannot even type properly cuz knew keyboarddd
But do I need to await it or not?
Ignore her, she has those so she feels like everyone has one
yes
you got to
so ignore this?
change def name to async def name
that code wont even run without a non-zero status code so
and call it using asyncio, or just use a setup_hook
Where?
wait wait wait
im confused sorry
Its a command, why tf do u not have an async command function
it's a command?
its old code
if it was dpy would have raised ajn error
just trying to load cogs in dpy 2.0
make it async def unload
It has it?
Yr error says otherwise
@client.command()
async def load(ctx, extension):
await client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
await client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await client.load_extension(f'cogs.{filename[:-3]}')
``` this is just what I got
Indent goes brrrrrrrrrr
idk man its old code idek
Indent was the same, be it old or new
How does it need to be then lol
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
I know what indent is yes
anyone know how i could check if i had any dms with a user when they dm the bot
like if the bot said anything
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns a string representation of the channel
isinstance(msg.channel, discord.DMChannel)
.channel
??
Thanks
anyone know how i could check if the bot had any dms with a user when they dm the bot
Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)
But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```
Json file:```json
[
"test"
]
ok ur req sound very strange to me wdym
** if i had any dms with a user**
and they dm bot
so they stop dm with u talk to bot and dm bot and bot reply to them
cuz i only want the bot to respond to them once and if they dm them again it won't respond
how the bot gonna know they talk with u or not u talk in a bot monitored channel?
!d discord.DMChannel.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...
class Bot(commands.Bot):
def __init__(self):
super().__init__()
async def on_ready(self):
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
await client.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded {filename}")
except Exception as e:
print(f"Failed to load {filename}")
print(f"[ERROR] {e}")
``` shouldn't this work too?
horrible don't do this
Looks like youβre on 2.0, why not use setup hook?
first of all add prefix intents in init
Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.pop(arg)
But i get this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer ```
Json file:```json
[
"test"
]
Can anyone help me pls?
@bronze jackal
Pop takes an integer
hey, any1 can help me? im using replit to this rn, but this dont run
If you want to remove by string, use remove
Give it time
what don't run its shows its running have some patience
Idk just trying to load cogs thats all on 2.0
Okay, well use setup hook
class Bot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.all())
async def load_cogs(self):
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
await client.load_extension(f"cogs.{filename[:-3]}")
print(f"Loaded {filename}")
except Exception as e:
print(f"Failed to load {filename}")
print(f"[ERROR] {e}")β
shouldn't this work too?
async def setup_hook(self):
await self.load_cogs()
the indents
fucked up
yeah but I got my prefix and intents here if you get me
how would i check if the bot sent any messages
that just stop
eh i can't do indents on phone
Youβd check the length of the DMChannel history, if itβs greater than 0, there has been messages
what u subclassing for then
later of this dont run
but i want to see if i sent any not the user
It was an example code
Then apply a filter
how would that look like
tf is the problem
async def main():
async with bot:
await load_cogs()
await bot.start(token)
asyncio.run(main())
!d filter
filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.
Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.
See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
do this instead of bot.run
b-b-bump
Can someone help me?
len(member.roles)
len(CTX.author.roles)
yep, according to asher, setup hook is inexistent
yeah so ashley gonna explain u the whole process
pls help
yeah so asher will explain what's the problem in my code
wait lemme see
!d sys.setrecursionlimit
sys.setrecursionlimit(limit)```
Set the maximum depth of the Python interpreter stack to *limit*. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
If the new limit is too low at the current recursion depth, a [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is raised.
Changed in version 3.5.1: A [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError "RecursionError") exception is now raised if the new limit is too low at the current recursion depth.
i hit that limit in codewars
when one lining some kata
@shrewd apexcan u help me? see the other imagen
how can i make my discoed bot move a channel to a catagory on a message
you have no flag to stop the recursion so open() is being called infinitely make a sort of disabled flag and return on that flag being true currently it's just calling open again and again
no errors?
no, that dont show errors
are the dependencies installed?
wait wtf are u actually trying to just run poketwos bot after cloning it?
u know poketwos resources are scattered all over the place also u can't just randomly clone a repo and expect it to work
the name is just a reminder about the bot, really the commands are differents
so u coded those cogs so that all have same name as poketwoπΏ
u prolly urself don't know what are even tokens needed to run all those cogs like mongo creds redis creds etc
the resources for the db the images emojis
half them are not even on that repo
they are scattered in different repos
how can i make my discod bot move a channel to a different catorgaory on a message
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
that's so horrible Asher
await channel.edit(category=1008790693327675463)
await channel.edit(category=category_channel_object)
would that work
kek and that's not all it's not written in python throughout either some parts are written in rust and a few other langs
@slate swan would this wok
what types does that kwarg accept?
let me see
CategoryChannel
no one saw anything π
it accepts Snowflake though
i am confused
the code i wrote doesnt work
await channel.edit(category=1008790693327675463)
Most API methods accept a snowflake because on a lower level thatβs whatβs sent over the API
Iβm willing to bet you can send a message with just an object, but discord.py prevents you from doing so because the type of a snowflake is unknown
it doesn't accept int, you should put the id in a discord.Object and pass that
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create βminiatureβ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectβs hash.
jesus, get some help
makes sense to have some parts in rust for efficiency!!
it not even in main code tho πΏ it just feels it was written to annoy PPL who try copying the whole code
I mean I understand the idea why using different languages but all that for a discord bot
git clone Asher/main 
i am not good at classes
discord.Object(918291892819219219)
so
category=discord.Object(id)
me keep my source private
I took that wrong for a sec
i meant it wrong that way
u thought correct
great minds think alike
you'll need to know about them, if you're interested check out https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc or https://docs.python.org/3/tutorial/classes.html#class-objects
so do mischievous ones 
who here know make bots about pokemon, i need help in a commands, well i need the command for spawn 
just copy smh
what have you tried
and what isn't working
the whole poketwo bot 
why error
@bot.listen()
async def on_message(message):
channel = str(message.channel.name)
user_message = str(message.content)
if channel == "juan-request":
if user_message != "":
new_name = "test"
await channel.edit(name=new_name)
what? but there is an if check?
you need to remove the current MinesweeperButton from the result of .nums_around
oh nums_around is not a method
but you get what im saying
n-n-no... im not-t?
wdym remove current button from nums_around
you're calling self.open() essentially
self.view.children[n] is self for some iteration
what? how?
but nums around dont containt number it self
for 0 its 1, 5, 6
no 0 in there
assert self.view.children[n] is not selfand see
is not works here?
why not
make sure you assert before calling open()
i hope im not that stupid
still same error, still interaction error
wasnt it a recursionerror
it was
can you send the stuff again i lost it
ok so take a button with pos 24 for eg
it will call open() for pos 23
which will call pos 24
and so on
if they're both zero's right?
if self.bombs_around is 0 for both yes
hello, i need help with this issue,
im using rapptz discord.py for my discord bot and it keeps saying
"Member" has no attribute to "avatar_url"
please help.
@bot.command(aliases=["s"])
async def snipe(ctx, member:discord.Member=None):
if member == None:
member1 = ctx.author
memberxd = ctx.author.avatar_url
member = ctx.author.mention
channel = ctx.channel
try:
view = discord.ui.View()
button = discord.ui.Button(label="", style=discord.ButtonStyle.secondary, emoji="βοΈ")
button2 = discord.ui.Button(label="", style=discord.ButtonStyle.secondary, emoji="βΆοΈ")
view.add_item(button)
view.add_item(button2)
await ctx.reply(mention_author=False, embed=discord.Embed(
description = snipe_message_content[channel.id],
color = color,).set_footer(
text = f"{member1} β’ deleted a few seconds ago").set_author(
name = snipe_message_author[channel.id],
icon_url=memberxd), view=view)
except KeyError:
await ctx.reply(mention_author=False, embed=discord.Embed(
description = f"βΉοΈ {member}: no **recently** deleted msgs",
color = 0xfaa61a))```
avatar.url
ctx.author.avatar.url there is a different error
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'```
You're using 2.0.0a right?
im not sure, how do i check?
if you're not sure then it's most likely a no but you can check by printing discord.__version__
if it's 1.7.3 you can upgrade by pasting pip install -U git+https://github.com/Rapptz/discord.py into the terminal
yes im using 2.0.0
I'm reviewing ur code again, but in the meantime, I assume u have the members intent
then they don't have a custom avatar
you should use display_avatar attribute
ctx.author.display_avatar.url
@vocal snow is this correct?
ye
alr thanks
are people still generally using discord.py after they resumed development? or are there other forks or libraries that people seem to prefer? i have a few bots i've been developing using discord.py and wondering if there's any good reason to switch now that development is continuing?
Discordpy going out of business gave the other forks and libraries a standing chance. Before they were practically unheard of and nobody used them. Now we actually have choices. A good reason you would use something other than discord.py is you donβt trust the longevity of it anymore. Going out and coming back in made a lot of people lose trust that will take work to earn back. Some people prefer the implementation details, or just for a change. I suggest try them out and see what you like, but there are a lot more resources for dpy and people helping (myself included, I primarily help with dpy)
got it, thanks appreciate the context. is there a fork or library you feel stands out a bit? i've read some decent things about pycord, and i like that it seems the syntax is pretty much the same. also read some good things about hikari but not sure if i want to dig into a completely different library yet
I donβt know where you read that pycord was good but I assure you itβs not. It has a lot of issues, most can be dealt with. The toxic community is a pretty big turnoff. Hikari, as you know, is completely different. The biggest fork at the moment is disnake, followed by nextcord
But personally, I donβt see any reason to switch
haha ok thanks for pointing that out. granted i haven't done a lot of digging yet, but happened to see it recommended in a few stack overflow answers and the docs looked decent at first glance
i'll check out disnake and hikari but i'll likely end up sticking with discord.py until i find a reason not to
Hey, i try to create an command for a todo list. I have a json file with some words. When I enter the command and a word the discord bot should delete the word from the json file. ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")
Json file:```json
[
"test"
]
But the bot dont delete the word. Can anyone help me pls?
you need to dump the updated dict to the file
!d json.dump
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
Okay but i dont know how i have to use json.dump
^
obj is the dict, fp is the file object (which you can get with open())
So?
@bot.command()
async def v(ctx, arg):
with open("user.json", "r") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")
json.dump(read, f)
But i get now this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnsupportedOperation: not writable
class MenuTest(discord.ui.View):
def __init__(self, ctx, difficulty):
self.context = ctx
super().__init__(timeout=0)
if difficulty == 1:
self.boss_choices = [
discord.SelectOption(label="Hawk", emoji=":one_star:", description="Hawk"),
discord.SelectOption(label="Bear", emoji=":one_star:", description="Bear"),
discord.SelectOption(label="Wolf", emoji=":one_star:", description="Wolf")
]
elif difficulty == 5:
self.boss_choices = [
discord.SelectOption(label="Seraph", emoji=":one_star:", description="Seraph"),
discord.SelectOption(label="Azazel", emoji=":one_star:", description="Azazel"),
discord.SelectOption(label="Gilgamesh", emoji=":one_star:", description="Gilgamesh")
]
@discord.ui.select(placeholder = "Choose a boss", options = self.boss_choices)
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
if select.values[0] == 'Hawk':
await interaction.response.send_message('You picked boss 1 :one_star:', ephemeral=True)
elif select.values[0] == 'Bear':
await interaction.response.send_message('You picked boss 2 :one_star:', ephemeral=True)
elif select.values[0] == 'Wolf':
await interaction.response.send_message('You picked boss 3 :one_star:', ephemeral=True)
is it possible to pass self to @discord.ui.select's options?
So? py with open("user.json", "w+") as f:
No, but it looks like youβre looking for a more dynamic solution. You should consider subclassing
See my example in the discord.py repo
Should be under βviewsβ and is called βdropdown.pyβ
alright, thank you!
can some one make me a discord bot or help
how can we help
My Bot delete now every word :c ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "w+") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")
json.dump(read, f)
because im pretty sure the mode is a+ for appending and reading
write deletes everything in the file and passes what you provided
yes?
use r+, seek and truncate
a+ will have the pointer at the end to begin with so the load will fail
yeah
i checked stack and the methods to remove a line in a file are quite interesting
When i use a+ my bot copy another word ```py
@bot.command()
async def v(ctx, arg):
with open("user.json", "r+") as f:
read = json.load(f)
if arg in read:
read.remove(arg)
print("123")
json.dump(read, f)
with open("user.json", "r+") as f:
data = json.load(f) # moves pointer to end
f.seek(0) # move to beginning
f.truncate() # remove everything
# mutate data
json.dump(data, f) # dump new data
f.truncate()
``` but i dont want remove everything
yes you do
so that you can dump the new data
after editing it
otherwise you will have old data and new data in json file
Ahhh thank you this work < 3
How can I make it so that only a specific role can use a command?
!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")...
class Dropdown(discord.ui.Select):
def __init__(self, difficulty):
if difficulty == 1:
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red'),
discord.SelectOption(label='Green', description='Your favourite colour is green'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue')
]
elif difficulty == 2:
options = [
discord.SelectOption(label='One', description='Your favorite number is one'),
discord.SelectOption(label='Two', description='Your favorite number is two'),
discord.SelectOption(label='Three', description='Your favorite number is three')
]
super().__init__(placeholder='Choose your favourite colour...', options=options)
async def callback(self, select, interaction):
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
class DropdownView(discord.ui.View):
def __init__(self, difficulty):
super().__init__()
self.add_item(Dropdown(difficulty))
so after subclassing my select menu, im getting that options is referenced before assignment so did i not handle it correctly?
i define options based on the difficulty i have inputted
i tried with my code but it didn't work so i'm working off of the example
Hey that looks familiar! Is this where the error is?
Or is it with your own code?
i tried to make the select menu dynamic following your example but i'm getting an error with super().__init__(placeholder='Choose your favourite colour...', options=options)
i think in my code it was the same problem
Maybe the difficulty is not 1 or 2
i also tried having an else statement that also changes it but it gave the same error
oops not same error
it just went to the else statement
What other error do you get if the else statement also defines the options?
correction, i didn't get an error it just ignored my first if statement
so its giving me the numbers option always
So it works as expected with an else?
no matter what i input it with an else statement, it always gives me the option that is in response to the else statement
even with 1 as my difficulty it will skip to the else statement
idk if that makes sense what i just said
It does, how are you defining difficulty?
I have a hunch on what the issue might be
But I can't be sure without more information
uh what do you mean, in my slash command difficulty is just a command argument and for the views i just have it defined in init
so in my View class self.add_item(Dropdown(difficulty))
and in my command its view = DropdownView(difficulty)
should i be referring to it as self.difficulty
What type is it?
I see how you're passing it down up from your command down to your dropdown, but I'm concerned with it's datatype at the top level slash command handler
uhh do you mean what type difficulty is? its an integer
@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: int):
view = DropdownView(difficulty)
await ctx.send('aaaahhhhh', view=view)
I'm not sure how your library of choice handles this (it's not d.py from what I can tell) so try printing out the type of difficulty
with type(difficulty)
!e
def my_function(int_arg: int):
print(f"{type(int_arg)=}")
my_function("it's not an integer lol")
in my slash command or in the select view? im using pycord
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
type(int_arg)=<class 'str'>
In your slash command
bots
uh it says its None
how can i hit the copy buttion to copy th url on mobile
that's the problem then
is there any reason why it would be None though?
Can you send a picture of you invoking your slash command?
1 second, im trying again with optionchoice
invite a bot?
Hmm okay. Seems like a bit of a pycord issue honestly, you'll need to figure out how to get it to return your arguments as integers
wym?
yeah that kind of looks like the command isnt registered with any parameters at all
is there a way to check if a dictionary's keys is in the message's content, like $check keyname
@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: int):
print(type(difficulty))
view = DropdownView(difficulty)
await ctx.send('aaaahhhhh', view=view)
is there any reason it shouldn't show up in this command?
i was just ignoring that because i didn't know if it was something wrong with my command
try annotating it with discord.Option
I think that's what pycord uses
how do i check whether a channel exists in a server
right now my idea is to try except bot.get_channel
based on what, name, id
id
Was thinking the same thing
then guild.get_channel is what you want
how can i invite discord bots on mobile
just use the invite link and should be fine π€
also, how do I catch the exception? Do I catch disnake.ext.commands.errors.CommandInvokeError or AttribiuteError
or is there a better way
i cant reach it
guild.get_channel doesn't raise an exception. You can check if it returns None or a valid channel
given their github examples i dont think its necessary: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py
ooo yeah ur right
Thanks i overlooked a part of my code
hmm you're right
I wonder if they have parameters optional by default
async def whatthe(ctx, difficulty: Option(int, 'Pick a number')):
still isn't giving me the argument parameter
how can i invite my bot with out the url generator
you can't, the authorization part is important
can i use the client id
bue!!!!!!!!
gn
burps
can you send your full code?
!paste
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.
class Dropdown(discord.ui.Select):
def __init__(self, difficulty):
if difficulty == 1:
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red'),
discord.SelectOption(label='Green', description='Your favourite colour is green'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue')
]
else:
options = [
discord.SelectOption(label='One', description='Your favorite number is one'),
discord.SelectOption(label='Two', description='Your favorite number is two'),
discord.SelectOption(label='Three', description='Your favorite number is three')
]
super().__init__(placeholder='Choose your favourite colour...', options=options)
async def callback(self, select, interaction):
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
class DropdownView(discord.ui.View):
def __init__(self, difficulty):
super().__init__()
self.add_item(Dropdown(difficulty))
@bot.slash_command(description = 'aaaa')
async def whatthe(ctx, difficulty: Option(int, 'Pick a number')):
print(type(difficulty))
view = DropdownView(difficulty)
await ctx.send('aaaahhhhh', view=view)
this is what im trying to workout right now
are you creating more than one instance of discord.Bot or whatever
what do you mean?
bot = discord.Bot(debug_guilds=[os.getenv("GUILD")], intents=intents)
and that's the only one which you're running right
yea
i dont think getenv can return an integer
oh you're right
based on their docs debug_guilds is meant to take list[int]
https://docs.pycord.dev/en/master/api.html#discord.Bot.debug_guilds
id figure its something to do with command synchronization
try adding int() around your getenv call and restart your bot, maybe pycord's not syncing correctly because of the mismatched type
i tried manually inputting my guildid and still isn't showing up
maybe remove the debug guilds altogether, they sync instantly anyways
oh, that seemed to do it
but that seems weird that it didn't work with the debug guild?
yes, very weird
can you check your integrations tab in server settings to see if there's two duplicate commands?
no just 1 of that command
huh
the id you were giving it was an int and not a string right (no quotes)
i guess you've been looking at the global slash command the entire time
yeah it was an int
guild id is correct yeah?
probably py-cord has some weird syncing mechanism
i much prefer syncing manually for this reason
wym manually syncing
How am i able to do this?
you can control how and when you update your application commands
in py-cord, you create a command with the decorator and it's automatically updated in discord for you
These are subcommands
Oo cool ill look into it
How does that work π€¨ I wasnβt aware that decorators could be asynchronous
oh really, thats neat
no no i worded that wrong
more like, the decorators add the commands to a pool and then they are synced with bot.run or whatever
That would explain it
which is convenient sometimes but also really inconvenient
I sure hope they arenβt actually syncing in the decorator
Thatβs not very pythonic
But knowing pycord theyβre probably doing some weird hacky way
yep
would you mind sending the doc regarding the decorator?
thank you !
@commands.group(invoke_without_command=True)
async def parent_command(self, ctx):
await ctx.send("Parent command!")
@commands.has_role("mod-role")
@parent_command.slash_command(description="Make a voice channel that is privated")
async def create(self, inter:disnake.CommandInteraction, channel_name:str):
Trying to make subcommands for slash commands, but getting this error
Anyone got example code on how to make subcommands?
As they should (or shouldnβt? Iβm not good at English)
as they should, yeah
if they synced in the decorator it would be a lot of api calls π³
ur a legend tysm, how did i not find that
when in doubt, always check the docs π
π
S1 + S2
fstring
s1 + \ns2 work ?
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
na na i know about but i want to join 2 strings with new line
!e
x= "hello"
y = "world"
print(x+y)
print(f"{x}\n + {y}")
Do you hate fstrings
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
helloworld
Did they bully you
!e
x= "hello"
y = "world"
print(x+y)
print(f"{x}\n{y}")
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | helloworld
002 | hello
003 | world
Hello I know like beginner level python and am new to making discord bots, can you make a discord bot do something in accordance to a user's rich presence?
like if someone was playing a game and the game's rich presence said like "fighting this boss" the bot would say something only when that rich presence is happening to a user
or something like that basically
list index out of range why this error ?
@commands.command()
async def ad(self , ctx,*, name_and_dis):
x = name_and_dis.splitlines()
info = "ok\n"
i = 1
for y in x:
z = f"{x[i]}\n"
info = info + z
i= i+1
await ctx.send(f"{info}") ```
!e
my_list = ["abc"]
print(my_list[3]) # print element 3 of my list
# uh oh. My list only has one element therefore index 3 does not exist
@full lily :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
can you send a traceback
Traceback (most recent call last):
File "D:\ph\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Kamal kishore\Desktop\Project 0\commands\economy\store.py", line 41, in ad
z = f"{x[i]}\n"
IndexError: list index out of range
The above exception was the direct cause of the following exception:
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "D:\ph\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range```
I think you would want to start with i=0
info = "ok\n"
for y in x[1:]:
info = info + f"{z}\n"
you could do this
orrrr
i think you just want
is this a list of strings?
yes
@commands.command()
async def ad(self , ctx,*, name_and_dis):
x = name_and_dis.splitlines()
await ctx.send(f"ok\n{"\n".join(x[1:])}")
try this
[1:] mean ?
means everything starting from index 1
oh k k tring
You can't have double quotes inside double quotes
You also can't have a newline inside the placeholder part of fstring
Yes, enable presence intents and you can access the user's activity with user.activity
(f"ok\n{'\n'.join(x[1:])}") ????????
@limber bison
oh k
thank you π
And go to sleep bro π
π
how would I restart my entire bot with a command? this is what i currently have
await self.bot.close()
self.bot.loop = asyncio.new_event_loop()
token = config['token']
self.bot.start(token)
but it says that RuntimeError: Event loop is closed
the exception is on the close() function
How would you define a restart
Do you want to logout and login
Or restart the script
SyntaxError: 'await' outside function in this
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'lol':
if user_message.lower() == 'is le dead':
await message.channel.send(f'lol lod')
return
elif user_message.lower() == '!game':
response = 'what game do you want to play? we have random number, '
client.run(TOKEN)
this chunk is broken
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i hate my keyobard
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'lol':
if user_message.lower() == 'is le dead':
await message.channel.send(f'lol lod')
return
elif user_message.lower() == '!game':
response = 'what game do you want to play? we have random number, '
client.run(TOKEN)
i did it for u :)
thx
Ty. Can see the indentation now
The second if statement isn't inside the event
Is that a formatting error or
if message.channel.name == 'lol':
if user_message.lower() == 'is le dead':
await message.channel.send(f'lol lod')
return
elif user_message.lower() == '!game':
response = 'what game do you want to play? we have random number, '
if the indentation on discord is correct, you need to tab forward this entire section, as the first if statement isn't in the on_message function
Could we avoid spoonfeeding in the future please? There's little to no educational value in that and only puts more work on people helping in the future
alr
I think they were just formatting it, not solving it
Well it was an indentation problem so formatting and solving are synonymous in this case
How do I make a popup window?
No no i mean formatting it with the codeblock, not fixing the indentation
A modal you mean?
Oh right it's the same
lol ofc they'd call it something weird
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
ty
Haha fr
Oh no, can't call it a promptwindow or a popup or something common.
Have to call it a 'modal'
Well to be fair "popup" has a negative connotation, and a prompt window is usually associated with the OS/DE
inputmenu
See this example I made if you want to know how to use it: https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py
ty
Looks like Danny moved it from it's original position under examples so now it looks like he made it instead of me π
Heck I don't even know if this is the one I made lol, my memory is terrible
Β―_(γ)_/Β―
if it works it works
Oh okay
I see. So it's sorta like an embed (sorta I said.)
where if you want a new input field, you create a new variable with all the things
Before someone jumps down my throat. I said sorta.
I'm gonna have to say no on that one, but I get your point about sorta π
where an embed is: embed.add_field(blah blah) this is mynewvariable = inputthingy(blah blah)
More or less, yeah
and if I wanted a new field, I'd add:
newfield = discord.ui.TextInput(label='newfield', placeholder='New field placeholder',)
between the feedback and name.
not too much different to an embed in this regards
How many input fields can I have on 1 thing? or is it based on character limits?
Is it possible to send an ephemeral message when a user joins your server?
Whats the documentation for ephemeral messages?
If you know how to send ephemeral messages, you can just do a check for on_member_join() and send the message then.
No specific documentation, certain methods just have an ephemeral kwarg
Not possible unfortunately. Ephemeral messages need to be responses to interactions
Really? D: dang
Ah, that's unfortunate
Yeah most of discord's new features are very limited (take modals for instance, they only support the text inputs)
I think they do in some really new version? I heard people talking about them but it's more rumor than anything
Hey, is it possible to get a users about me section using discord.py?
Neat. Well if it ever becomes a thing I'll be the first to start updating all my bots. For now I got a new bot to make! π
Good luck with that! Just make sure you're on 2.0 for all the new stuff, and it's not on pypi so you'll have to install it manually (pip won't work)
How do I check my discordpy version?
discord.__version__ anywhere in your code
I did pip freeze, remembered that was a thing after I asked.
Preferably in an on_ready or something similar:
@bot.even
async def on_ready():
print(f"Using discord.py version {discord.__version__}")
I don't recommend checking it with pip because pip could point to many different things, venvs, etc. So you really can't be sure the one shown in pip is the one you're really using
Venvs would solve that problem, of course. You should always be using a venv when working with python
Looks like you're good then
Good coz I really didn't want to have to update all my bots again
Hey, I needed to ask, is it possible to get a users about me section using discord.py?
!d discord.Member.activity I might be wrong though, give it a test
property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
I'm not talking about the activity, I'm talking about a user's about me section in their profile.
I know, but I believe that's what it's under
how do you get the ID of emotes in discord? trying to have my bot check for a reaction of a certain emote
e.g β
Default emotes like these don't have IDs
You can just compare them like so:
emoji: discord.Emoji = # pretend this is the emoji that the user reacted with
if emoji == 'β':
...
Gotcha, how do you get these though? i can't copy them.
CTRL + C
β
i know that dude, it's just that when i try to paste it in pycharm, it pastes as * instead.
Dont use pycharm
no need to get aggressive
I'm not? emotions are not conveyed well over text.
you could try pasting it directly into the file
Try using vscode
Windows key + >
same thing
Pycharm gives potential errors though, i don't know if vscode does that
you could also do windows key + ;
oh neat
try using the unicode perhaps
windows + < is neat. I started pressing all the keys
π
the star is U+2B50
iirc
\U0002B50
@slate swan there's also a plugin for emoji support- https://plugins.jetbrains.com/plugin/9174-emoji-support-plugin
Intellij plugin for supporting auto-complete for Emoji.
Hmm, the windows + . doesn't have a search function, shame
What do I need to add to the end of a function to remain PPEP8 compliant? async def makenote(orgid: int, note: str, shared: bool, bmid: int): is what I have atm. I know you are suppose to add something but idk what
you could add return annotations
How?
async def some_command(ctx: discord.Context) -> None:
oh
yeah, it's just some annotation that says what the function returns
async def makenote(orgid: int, note: str, shared: bool, bmid: int) -> dict:
```?
I'm 99% sure it's always gonna be None for discord.py commands
Also what's the difference between:
""" Whatever this is suppose to be. """
and
# Commented out
I've always used # to make comments, but I often see the triple quotes as well
so idk the difference..
Is there any benefit to using them over #?
it's still read by the interpreter
Or is it like a preference thing?
comments are ignored, triple quotes are read
by the interpreter at least
that's as much I know
So, until we're told otherwise, it's a preference thing
wait!
@slate swan
That's what it does π
Oh fuck yeah.
Always wondered how to edit that stuff.
Heyyy @sick birch
Traceback (most recent call last):
File "C:\Users\Declan\Desktop\discordbots\notesbot\testbot.py", line 54, in <module>
async def feedback(interaction: discord.Interaction):
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 834, in decorator
self.add_command(command, guild=guild, guilds=guilds)
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 271, in add_command
guild_ids = _retrieve_guild_ids(command, guild, guilds)
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 106, in _retrieve_guild_ids
return {guild.id}
AttributeError: 'int' object has no attribute 'id'
``` I tried running your code and like. wot.
is it coz my discord thingy isnt up to spec?
how are you defining guild?
I copied your code and just set TEST_GUILD to my guild id
All of a sudden I'm getting Interaction object has no attribute 'edit_original_message'?
It only happens in production on my actual server, despite the code being exactly the same as my testing bot where it doesn't happen
Should it be:
TEST_GUILD = discord.Object(794837147068792862)
or
TEST_GUILD = 794837147068792862?
The former
Alright I did that. Now I get another error lol
I just want to see how it works. ;-; is this slash commands?
Role= discord.utils.get(member.guild.roles, name="your role")```
Then you gotta make your bot give role to the user whenever they use the command
can i invite a bot via client id
It's edit_original_response, remember I pinged you about it yesterday
you sure? it works on my dev version and I'm looking at the source code right now and seeing edit_original_message
Yeah it's a new version
gahhhh
Usually your dev version will be a few versions ahead
can i invite a bot via client id
No
Need help with setting up boost bot
I see, I think I just accidentally auto-updated when I added another dependency recently by installing my whole requirements file haha
oh @sick birch I dont think I can do slash commands π¦
await ctx.author.add_roles([item["role"]])
error :
'list' object has no attribute 'id'
π³
dead ?
yo how easy is it to set up a bot?
not coding part, setting up one to take the code?
import discord, os, json
from discord.ext import commands
with open('config.json', 'r') as f:
config = json.load(f)
TOKEN = config.get('TOKEN')
Prefix = config.get('PREFIX')
Invite = config.get('Invite')
intents = discord.Intents.all()
client = discord.Client(command_prefix=Prefix, intents=intents)
@client.event
async def on_ready():
print('Bot Online')
@client.command()
async def invite(ctx):
await ctx.send(f"Add the bot here:"+ Invite)
client.run(TOKEN)```
ERROR:
Traceback (most recent call last):
File "c:\Users\Clicks\Desktop\Stuff\test.py", line 22, in <module>
@client.command()
AttributeError: 'Client' object has no attribute 'command'
Fairly simple
Just define role separately and add it
how ?
id have role id in my db
role = discord.utils.get(member.guild.roles, name = "Member"
Import get from discord.utils tho
could you dm me a straightforward video on only setting it up, and how to add the code you make from vs code or something like that into the bot?
And then replace (item[role name]) to (role)
There are plenty of videos on yt tho
no, creating a bot doesn't need any code
not working
discord.Client doesn't have commands, discord.ext.commands.Bot does
i dont believe that, why else would there be a bot dev in a python server? and i've tried to m ake one before
as i said, "creating"
not running and programming it.
yes thats what i need to know, create the bot
await ctx.author.add_roles(item["role"])
'Int64' object has no attribute 'id' ?
https://discord.dev -> applications -> new application ->enter bot name -> ( a page opens ) -> click on "Bot" menu -> "Add bot" option
thats all
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Send the code of what you changed
WOOO!! Progress! π https://www.youtube.com/watch?v=U0Us5NHG-nY <- gave me a lot of help
WOAH, what's that
MODALS!!
whats it ?
A modal
Now for the fun part.
Hooking it all up in 1 go and finding all the bugs I made π
funtion ????????????
What could go wrong by pasting in a heap of code without testing it as I go?
It looks like this
You can get it to show on a user's screen by responding to an interaction (slash command, button press, etc)
It's actually not too new of a feature, not sure how many people haven't heard of it yet
Probably because it's rarely used.
I only found out about it because my friend used it on his server
and I was like 'Wow. That's gonna be a pain to use.' and here I am, 2 months later.
suffering that pain
That too, it's also incredibly limited like I mentioned before. If they added buttons, select menus, and a bunch of other cool components I'd seriously be considering it
oh modals
select menus possible but shows only on pc
Quick question.
def myfunction(value1, value2, value3):
pass
Do I have to do them in order? Or can I do:
myfunction(value3=1, value1=2, value2=3)?
You can mix them up, but only as long as it's not a positional only argument, and you specify the keyword argument
π I pretty much got it all working. It's now hooked up to my new notes bot.
Ty @sick birch for your help.
Awesome! Glad to hear
I just hope nobody asks me to convert all my bots to slash commands lol
All my bots are contained into 1 discord.
What do you mean?
how would I restart my bot from a command? this is what I have currently
await self.bot.close()
self.bot.loop = asyncio.new_event_loop()
token = config['token']
self.bot.start(token)
but it gives me a RuntimeError: Event loop is closed error
1 server*
Ah yeah, that's not a problem
Restart how? Turn the script off and on or just disconnect your bot from the gateway and reconnect?
disconnect from the gateway and reconnect
How do I get the discord name/id of the person running the command? Usually I'd do ctx.author or whatever. but im using an interaction
@celest sparrow Im using interactions, there is no ctx.
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
interaction.user
Given discord.py, that is
i posted my code, and thats what i'm using. using the nextcord library if that helps
Right. There's no need to mess with the event loop though, just use the .close() coro
it gives the same error either way
yea
Get rid of the asyncio.new_event_loop() stuff it's messing with the event loop
Could you paste the full traceback?
Traceback (most recent call last):
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
cli.main()
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
runpy.run_path(target, run_name="__main__")
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 321, in run_path
return _run_module_code(code, init_globals, run_name,
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 135, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "c:\Users\vovan\.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 124, in _run_code
exec(code, run_globals)
File "c:\Users\vovan\OneDrive\Desktop\projects\Kaid\main.py", line 100, in <module>
bot.run(token)
File "c:\Users\vovan\OneDrive\Desktop\projects\Kaid\env\lib\site-packages\nextcord\client.py", line 793, in run
future = asyncio.ensure_future(runner(), loop=loop)
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 615, in ensure_future
return _ensure_future(coro_or_future, loop=loop)
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 636, in _ensure_future
return loop.create_task(coro_or_future)
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 436, in create_task
self._check_closed()
File "C:\Users\vovan\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
@commands.has_permissions(administrator=True)
@commands.command()
async def restart(self, ctx:commands.Context, module):
if 'bot' in module:
try:
config = openConfig()
await self.bot.close()
#self.bot.loop = asyncio.new_event_loop()
token = config['token']
self.bot.start(token)
embed = nextcord.Embed(title="Reload", description=f"Reloaded {module} successfully!", color=0xec0a96)
await ctx.send(embed=embed)
except Exception as e:
print(e)
await ctx.author.send(f"Restarting bot failed! | **Error :** `{e}`")
else:
try:
self.bot.reload_extension(f"cogs.{module}")
embed = nextcord.Embed(title="Reload", description=f"Reloaded {module} successfully!", color=0xec0a96)
await ctx.send(embed=embed)
except Exception as e:
print(e)
await ctx.author.send(f"Reloading extension failed! | Error : `{e}`")
Yeah looks like you're trying to do API operations after your bot is closed
wdym?
e.g await ctx.send(...)
after
await self.bot.close()
whats the point of restarting the bot? you can just reload your cogs whenever you want to
bot.close() closes the connection from gateway and closes the passes the bot.run() line as well, so you cannot restart the bot that way
π
with open("blacklist.json") as file:
blacklist = json.load(file)
BlacklistedUsers = blacklist.get('ids')
@client.group()
async def ablacklist(ctx):
text=f"There are {len(blacklist['ids'])} users in the blacklist"
await ctx.send(text)
@ablacklist.command()
async def add(ctx, member: discord.Member = None):
user_id = member.id
if user_id in BlacklistedUsers:
await ctx.send("User Already Blacklisted")
return
add_user_to_blacklist(user_id)
embed=discord.Embed(title="User __Blacklisted__", description=f"**{member.name}** has been successfully added to the blacklist", color=0xff0000)
embed.set_footer(
text=f"There are now {len(blacklist['ids'])} users in the blacklist"
)
await ctx.send(embed=embed)```
It sends *both* `text=f"There are {len(blacklist['ids'])} users in the blacklist" await ctx.send(text)` & `embed=discord.Embed(title="User __Blacklisted__", description=f"**{member.name}** has been successfully added to the blacklist", color=0xff0000) embed.set_footer(text=f"There are now {len(blacklist['ids'])} users in the blacklist"`
π
i like snaek
Is python use c in background ?
so what do I use instead?