#discord-bots
1 messages Β· Page 1070 of 1
str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
it's from the variable though
image doesn't send
what if the bot stops? you do stuff in the on_disconnect event too?
It's better to just use proper db
having large amount of data in memory is not always viable though
Well the script would still run, no?
Ik ik
Agreed tho ngl
But then, bots like reaction roles do store everything in the cache so that everything is fast and they don't have to query their DB repeatedly
@maiden fable How can I replace spaces with a certain character?
^^^
bump
ch = "%"
lyrics = lyrics.replace(' ', ch)
this didn't seem to work
Do u have an error handler?
A few
!e
ch = "%"
lyrics = 'hello world'
lyrics = lyrics.replace(' ', ch)
print(lyrics)
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
hello%world
!e
print(" Hello ".replace(" ", "%"))
@maiden fable :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print(" Hello ".replace(" ", "%")
003 | ^
004 | SyntaxError: '(' was never closed
'
Guys how can we make a !e comamnd like @unkempt canyon have?
!source e
Run Python code and get the results.
@maiden fable you probably will know why this aint work lemme show the full code
@client.command(aliases=['ly'])
async def lyrics(ctx, lyrics):
ch = "%"
lyrics = lyrics.replace(' ', ch)
r = requests.get(f'https://some-random-api.ml/lyrics?title={lyrics}')
r = r.json()
title = r['title']
author = r['author']
links = r['links']['genius']
lyricss = r['lyrics']
thumbnail = r['thumbnail']['genius']
em = discord.Embed(url=f"{links}", title=f"{title} by {author}", description=f"{lyricss}" + "\n\n", color=discord.Color.blue())
em.set_thumbnail(url=thumbnail)
em.set_author(name=f'Result for: {title} by {author}', icon_url='https://images-ext-2.discordapp.net/external/ifcJsOb6tpFUWKRg2H5oUxp7RONA6nSV2ajXJ8-NP1s/%3Fformat%3D2500w/https/images.squarespace-cdn.com/content/v1/5aa2ed3f5b409b04f26f8580/1521864384033-QCLP1SKYQBAHQOVV3TGO/genius%2B4.png?width=582&height=582')
await ctx.send(embed=em)
added this, didn't raise an error
@maiden fable
@command(name="eval", aliases=("e",))
@guild_only()
@redirect_output(
destination_channel=Channels.bot_commands,
bypass_roles=SNEKBOX_ROLES,
categories=NO_SNEKBOX_CATEGORIES,
channels=NO_SNEKBOX_CHANNELS,
ping_user=False
)
async def eval_command(self, ctx: Context, *, code: CodeblockConverter) -> None:
"""
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!
"""
await self.run_job("eval", ctx, "\n".join(code))
Here is source code of
Which libraries do i need to import for it?
typehint lyrics as str
!e
from urllib.parse import quote
print(quote('hello world'))
use that
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
hello%20world
its supposed to be %20 for space char
How to start the ban function from @bot.event?
huh
urllib.parse.quote will do all conversions for you :)
so I can just do
lyrics = quote(lyrics) ?
yes
Isn't that easy. U gotta read all the code
?
Lemme see
Did u add that everywhere?
Like every error handler
didn't add that in the ones which were interaction handlers
Add it everywhere
it's only getting the first word still
like if I do !ly sky carti It's only using sky
do ctx, *, lyrics
what does the * stand for? is it just all
How to start ban from event decorator?
@bot.event
async def on_raw_reaction_add(payload):
if payload.channel_id == 977614786311372830:
if payload.emoji.name == "β
":
channel = bot.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
reaction = get(message.reactions, emoji=payload.emoji.name)
if reaction and reaction.count > 4:
await ban()
@bot.command
async def ban(ctx):
await bot.get_channel(977614786311372830).send("ban")
await ctx.guild.ban(BanMember, reason=BanReason)
Lol
@maiden fable error handler for a specific keyerror?
it just gives all args to lyrics
Oh
omg im so dumb
yes the file is save outside my cogs folder
are you loading your cogs?
yup
I am loading them on the on_ready event, tbh I need to start using setup hooks
I think that your class and you function shouldn't have the same name
I get this error
changed btw
very creative
how would i specify the dir
disconnected for long
yeah
the image is inexistent or the path is wrong
@glad cradle coulda ya help?
how would I make a error handler for a specific keyerror
uh? just use the get method on the dictionary object
and if it returns None, its not there
better than raising unnecessary exceptions
but I kinda want the exception
surround the part where you're accessing the key with try excepts
try:
v_key = dict_["key"]
except KeyError:
print(...)```
title = r['title']
author = r['author']
links = r['links']['genius']
lyricss = r['lyrics']
thumbnail = r['thumbnail']['genius']
thats where im accesing them
and?
and..?
and im telling you lmao
its better to use the get method here since you can set its default value withoit any unnecessary hastle, for example
title = r.get("title", "No title found")```
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
I see i see
if it finds the title key in the dictionary, it'll return that else it'll return the default value No title found
How to ban a user from on_raw_reaction_add?
π
How to detect if my bot have top role in server on not
anyone who's familiar with the subclassing of a help command and how it works?
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
this gist goes through that, have a look
I know, mine works, just wondering on how I can make it if I do a command it'll give me the usage automatically instead of having to hardcode it every time in every single command
Need this to work with subcommands aswell
But I can't seem to figure it out
write the useage in the doc string. And use that
or just use the signature
wait, let me provide you with an example: https://tokyotokyotokyotokyo.tokyo/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
If I type ,ban I want it to give me the same thing as when I type ,help ban
The help ban is done by the subclassing and mapping of the help command, but I can't seem to figure out how to make it for just a command (for instance: ,ban)
also trying to figure out how I can display the group commands automatically: https://tokyotokyotokyotokyo.tokyo/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
how to make xp and level system
@paper sluice lmk if you get what i mean
U can gte the command signature in ur error handler. Then u can format it
Guys how can we edit message when we click on button send in the message?
I saw a gist but that not worked
how do you mean?
also, that error message isn't an error handler, it's hardcoded into my command
Can someone help me fix code
@wet crystal this is what I was thinking, if the person clicks any of the item in the select menu, the button will be clickable.
class HelpView(discord.ui.View):
def __init__(self, mapping: dict, ctx: commands.Context):
super().__init__(timeout=180)
self.ctx = ctx
self.mapping = mapping
self.message = None
self.add_item(HelpDropdown(mapping, ctx))
@discord.ui.button(label="Home", emoji="π ", style=discord.ButtonStyle.blurple, disabled=True)
async def home(self, button: discord.ui.Button, interaction: discord.Interaction):
for item in self.children:
item.disabled = False
button.disabled = True
embed = await bot_help_embed(self.ctx, self.mapping)
await interaction.message.edit(embed=embed, view=self)
hm yes, that should work
Can someone help me
same issue?
Yes π
Guys i made a button command but when i click button says interaction failed and gets error
I saw this buttons command on GitHub
If I donβt manage thencsure
Oh ye I need a leave message aswell forgot
The error is pretty clear, probably the code on github is using another package, you have to check the dependencies of that code
what is difference between async and coro
hello
I checked it but doesnβt help much ngl
oh, like if u have an error handler u can get the parameter's name like
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, discord.ext.commands.error.MissingRequiredArgument):
error.param.name :: this gives the name of the missing parameter
another way could be that u make a function to format the signature like you do in your help command, and call that in the error handler
uhhh
an asynchronous function is called a coroutine. async is the keyword used to define an asynchronous function
it does not, the button remains disabled the entire time
item.disabled = False
button.disabled = True
ur doing button.disabled = True so it will stay disabled
"the" what?
oh wait nvm
It's using V2 version of discord. Py
And discord.ui view
i tried removing the button.disabled = True, and still it doesnt work
just set it to False :p
both to false?
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\TestiCanFly\main.py", line 279, in <module>
bot.run(TOKEN)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 511, in login
what is that
show your code
my code is so big ....
!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.
ah
Can anyone help me?
@discord.ui.button(label="Home", emoji="π ", style=discord.ButtonStyle.blurple, disabled=True)
async def home(self, button: discord.ui.Button, interaction: discord.Interaction):
for item in self.children:
item.disabled = False
button.disabled = False
``` still does not work
or should i remove the disabled = True at the top?
which lib are you using?
discord.py 2.0a
TOKEN = ""
bot = commands.Bot(command_prefix=discord.ext.commands.when_mentioned_or("i!", "hey bot ", "Δ°!", "Hey bot " "gΓΆster "), intents = discord.Intents.all())
prefix = bot.command_prefix
bot.remove_command('help')
bot.launch_time = datetime.datetime.utcnow()
"""
if __name__ == "__main__":
bot.load_extension("jishaku")
"""
u made this part a string, maybe thats the issue
in dpy, interactions come before buttons so ur signature would be
async def home(self, interaction: discord.Interaction, button: discord.ui.Button):
which line?
those things matter?
obv\
Whenever I click button it says interaction failed
ok
Do anyone have solution for it?
ah nvm mb, when do u get the error, as soon as you turn on the bot?
yeah, while trying to run
token has been invalid
i've regenerated the token and now working.... ty
ah k π
show code
how to mention someone from nickname with tag?
K
import discord
from discord.ext import commands
from discord.ui import Button , view
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 blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.style=discord.ButtonStyle.green
await interaction.response.edit_message(content=f"This is an edited button response!",view=self)
class channel(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(manage_messages=True)
async def test(self, ctx):
await ctx.send("This message has buttons!",view=Buttons())
async def setup(bot):
await bot.add_cog(channel(bot))
@paper sluice
who can help me?
Can someone help me
Do you got whats error?
Here is code
which lib?
discord.py 2.0
@robust fulcrum
in ur command button signature
At test command?
poor ryuga
please help me guys
Bruh
See at Google it's given
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Sed
i cant find answer there
Hey at discord.ui.Button(label) do i have to put all stuff like label
how to get User object from username
I guess can't
yes
normal emoji: <:emoji_name:emoji_id>
animated emoji: <a:emoji_name:emoji_id>
how to get emoji id?
type the emoji, the put this infront of the emoji - \
that will give u the format..
ah okayy thankss
np
π
it wont work with regular emoji.. im saying custom ones
@commands.command() # Create a command inside a cog
async def button(self, ctx,interaction: discord.Interaction, button: discord.ui.Button(style=discord.ButtonStyle.red,label="edited")):
view = discord.ui.View() # Establish an instance of the discord.ui.View class
style = discord.ButtonStyle.gray # The button will be gray in color
item = discord.ui.Button(style=style, label="Read the docs!") # Create an item to pass into the view class.
view.add_item(item=item) # Add that item into the view class
await ctx.send("This message has buttons!", view=view)
Will it work?
!lemon_bald this emoji is 
try it π€·ββοΈ
i know
also i have a question more....
how to get a random number? which lib?
random number?
like 1-5
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
ty
Can someone help me
Just ask away
Not working
@commands.command()
async def button(self, ctx):
view = discord.ui.View() # Establish an instance of the discord.ui.View class
style = discord.ButtonStyle.gray # The button will be gray in color
item = discord.ui.Button(style=style, label="Read the docs!") # Create an item to pass into the view class.
view.add_item(item=item) # Add that item into the view class
await ctx.send("This message has buttons!", view=view)
Where I ahve to put interaction thing
uhm, up he asked many times
whats the error
but i didnt find his issue
Guys what is wrong with this
Where I have to put interaction thing
In this
@dense swallowlol, how to get a bult-in emoji ?
use its unicode
where can i find
 like this
ty
What is wrong here
py-cord?
No.
Will anyone help me pls!
then?
If someone can assist me ping me or reply
issue?
sub class the buttons and view, it will be much easier
thats a custom emoji
The command doesnβt work
Let me try
send takes only 1 arg, it's not print, so use + instead of ,
or f strings
yeah
Thanks
wait, interaction doesnt even have that method though?
hello hooman
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!")
class channel(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def test(self, ctx):
await ctx.send("hello",view=Buttons)
Will it work?
yeah, but he is using slash commands
i think they're different
oh wait nvm
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Interaction is big problem
help pls
its not
Will it work?
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
try it?
no, it wont
But button comes but interaction fails
I made a class already
instantiate it
Oh k
thanks
welcome
But a guy told to make a class
uhm, yeah it'll work, but ya can just type await ctx.send("blah",view=Buttons())
what problem?
so how to use it
error?
readthedocs?
Me dont knowing how to remive await interaction.response.edit
Thing
Do you know how can I remove that
imagine using spaces π
omghowisthispossible
whoknowsmaybeyoudo
!d discord.Interaction.edit_original_message
await edit_original_message(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
this?
how to get ctx in task?
!d discord.ext.commands.Bot.get_context
await get_context(origin, /, *, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message or interaction.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
Note
In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
thx
how to import this?
I havnt
like myBot = commands.Bot(prefix='????')
I have client
oof
I dont write bot
channel name: yeah, who am i
I write script for my account, not bot, should I create Bot istance?
hmm bro
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I want to send messsages in my own server with friends
where are there illigal things?
you could at least use webhook...
creating self-bot
sorry, im not a professional pythonist((
its illigal?
yes
so why discord.py provide this ability?
automating your bot account is against discord Tos amd can get you banned.
it doesnt?
thats removed in newer updates
okey................
||it does in 1.7.3||
ohk
But that still doesn't change the fact that it's against the ToS
How to see server's cpu usage ?
and I decided to learn this lib a little bit for practice
htop :lemao:
?
nvm just joking
π€·ββοΈ
now im trying to learn some of ds.py for expirience
is it hard to create a bot to learn it ?
okay, i will make bot......
server's as in, which server?
how to make my bot send a message to a specific channel with id
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
thanks
Host (my VDS)
Can someone help me
what is the issue?
I didnt find it, maybe i should've scrolled even more...
psutil.cpu_percent(interval=None, percpu=False)```
Ngl psutil is one of the best modules out there
words = ['mwds', 'mds', 'smwnc', 'mdwc', 'change', 'massive']
list1 = ''
for word in words:
if word.startswith('mwd'):
#replace mwd to meaty wooly diamond
list1 += f' {word}'
print(list1)
how do i replace
Mind explaining what u wanna do?
Uh?
i want to change the word that start with mwd to be changed into meaty wooly diamond
Ah
mwds -> meaty wooly diamond s
Nvm
i dont want to replace it in the list
Then
res2 = ''
for items in itemss['items']:
my_emote = discord.utils.get(bot.emojis, name = items)
value = db[stats.userid + items]
if value > 0:
res2 += f"{my_emote}{items}: {value}\n"
because the some name != items
You could also do this ```py
words = ['mwds', 'mds', 'smwnc', 'mdwc', 'change', 'massive']
list1 = [f' {word}' for word in words if word.startswith("mwd")]
print(list1)
!e ```py
words = ['mwds', 'mds', 'smwnc', 'mdwc', 'change', 'massive']
list1 = [f' {word}' for word in words if word.startswith("mwd")]
print(list1)
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
[' mwds']
i still want to iterate through all of them
alright
i found a way to fix it
its freaking simple
if value == 1:
my_emote = discord.utils.get(bot.emojis, name = f'pog_{armor}')
res4 += f'{my_emote}pog_{armor}\n'
if value == 2:
my_emote = discord.utils.get(bot.emojis, name = f'iron_{armor}')
res4 += f'{my_emote}iron_{armor}\n'
if value == 3:
my_emote = discord.utils.get(bot.emojis, name = f'diamond_{armor}')
res4 += f'{my_emote}diamond_{armor}\n'
if value == 4:
my_emote = discord.utils.get(bot.emojis, name = f'meaty_wooly_diamond_{armor}')
res4 += f'{my_emote}meaty_wooly_diamond_{armor}\n'
if value == 5:
my_emote = discord.utils.get(bot.emojis, name = f'shiny_meaty_wooly_diamond_{armor}')
res4 += f'{my_emote}shiny_meaty_wooly_diamond_{armor}\n'
if value == 6:
my_emote = discord.utils.get(bot.emojis, name = f'shiny meaty wooly netherite {armor}')
res4 += f'{my_emote}shiny meaty wooly netherite {armor}\n'
if value == 7:
my_emote = discord.utils.get(bot.emojis, name = f'more shiny meaty wooly netherite {armor}')
res4 += f'{my_emote}more shiny meaty wooly netherite {armor}\n'
if value == 69:
res4 += ':beefy_sword: beefy_sword'
just change the my_emote = ...
oof
My god use a dict at this point 
π
yo how is everyone doing . can someone help me with my welcome system
!e
my_dict = {1: "first string", 2: "second string", 3: "third string"}
print(my_dict[1])
@placid skiff :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print(my_dict[1]
003 | ^
004 | SyntaxError: '(' was never closed
π
Del this
So it's clear
It don't let me press the button xD
Lol
aand what is the problem?
ah i see
Yea, there's a bug where u can't react with already reacted emojis, on mobile π
i tried before but it messed up with my first 2 commands and they looked the same so idk
So weird
I think that he saw that
I hope...
@loud junco
!e
my_dict = {1: "first string", 2: "second string", 3: "third string"}
print(my_dict[1])
Huh
Commands must initiate with the prefix xD
Ye lol
isnt hydro a prefix?
It's a mention lol
anyways what now
add pass
idk
https://paste.pythondiscord.com/imiboqecin Hi peeps do you know how to have this bot give out auto assign multiple roles members to when they join? in this code
BIG
https://paste.pythondiscord.com/odazicayof i need help fixing
Me?
maybe random with lowercase r?
^
You should be using random.randint
You've done something like from random import Random
Just import random
And then random.randint
How to get 1 user out of the reaction and ping him/her?
ah yeah, thanks
there is a member parameter
Hi peeps do you know how to have this bot give out auto assign multiple roles members to when they join? in this code
async def autoRole(self, ctx):
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
defRole = self.settings.getServerStat(server, "DefaultRole")
verify = int(self.settings.getServerStat(server, "VerificationTime"))
msg = '**__Auto-Role Management__**:\n\nWould you like me to auto-assign a role to new users when they join? (y/n/skip)'
if defRole:
auto = 'set to: **{}**.'.format(DisplayName.roleForID(defRole, server))
else:
auto = '*disabled*.'
if verify == 0:
verifyString = 'No delay before applying.'
else:
verifyString = '{} minute delay before applying.'.format(verify)
msg = '{}\n\nCurrently {}\n{}'.format(msg, auto, verifyString)
await author.send(msg)
gotIt = False
while not gotIt:
def littleCheck(m):
return author.id == m.author.id and self.check(m)
try:
talk = await self.bot.wait_for('message', check=littleCheck, timeout=60)
except Exception:
talk = None
if not talk:
msg = "*{}*, I'm out of time... type `{}setup` in the main chat to start again.".format(
DisplayName.name(author), ctx.prefix)
await author.send(msg)
return
else:
!code please
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.
u didnt call the function
!e
def foo():
return 'bar'
print(foo) # didnt call the function
print(foo()) # called the function
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
001 | <function foo at 0x7fd88a85cc10>
002 | bar
Ah yeah π€¦ββοΈ lemme test it
!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.
no
she means put the py to get syntax highlighting for python
Meaning?
```py
<your code>
```
Why i got None?
Show the embed code
Uh, yea that
guys can u help me with the welcoming text code
Hmmm
first as that
But idk What should i return ....
why are u dming? just send it in this chat
web browser discord.
Wdym dm it
i didnt
i am sending it here
huh, weird
But this what happens when i click send here
its the server
i'm making discord bot
@slate swan im almost done with my first command and ima show and u tell me how close i am to fixing it
nah i thought they used /msg
So
me2
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.
hm
So can i?
yes
You're becaming a star
error?
no
bye
what's wrong?
then what? you're just using command and nothing happins?
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await db.commit()
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id,))
await db.commit()
await ctx.send(f"Welcome Message has been set!")
return
if data is not None:
await cursor.execute("SELECT welcome TEXT FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await cursor.fetchone()
result = data[0]
await ctx.send(f"This server already has a Welcome Message set.", delete_after = 10 )
return``` i actually re writed but idk
You don't need to specify types in INSERT statement
It's only for CREATE TABLE and ALTER TABLE
Wtf is bot.say
what is this
a command maybe :lemao:
sets the welcome message
ok
btw
?
And yeah why wouldn't you add ability to overwrite existing welcome channel
UPDATE exists
@commands.Cog.listener()
async def on_member_join(self, member):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (member.guild.id,))
data = await cursor.fetchone()
if data is None:
return
else:
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (member.guild.id,))
channel_id = await cursor.fetchone()
channel = channel_id[0]
final = self.client.get_channel(channel)
await final.send(f"welcome {member.mention}")
else:
return``` since im doing a set message command do i need everything here
what is this
if data is None:
return
else:
if data is not None:
u dont need if data is not None:
if data is None:
return
else:
if data is not None:
``` very interestring construction
Ideally you shouldn't be creating a new connection each time
look for yourself
ye i wanna make it all into one connection bt i forgot how lmao
Ignoring exception in command gcreate:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 249, in gcreate
users = [user async for user in reaction.users()]
AttributeError: 'NoneType' object has no attribute 'users'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'users'
``` error ^
reaction is None
I've explained 5-6 times before, no way you're changing anything by saying that
uhh ill just wait till you guys are done
@client.command()
async def gcreate(ctx, mins: int, *, prize):
await ctx.send("Giveaway!")
end = datetime.utcnow() + timedelta(seconds=mins*60)
embed = discord.Embed(title=f"{prize}", description=f"React With :tada_cyan: to enter \nEnds: <t:{end.timestamp():.0f}:R> \n Hosted By: {ctx.author.mention}", color = discord.Color.random())
embed.set_footer(text=f"1 Winner | Ends {mins} min(s) from now!")
my_msg = await ctx.send(embed=embed)
reaction = await my_msg.add_reaction(":tada_cyan:")
await asyncio.sleep(mins*60)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = [user async for user in reaction.users()]
users.pop(users.remove(client.user))
winner = random.choice(users)
await ctx.send(f"{winner.mention}")
embed2 = discord.Embed(title="Winner!", description=f"{winner.mention}")
embed2.set_thumbnail(url=winner.avatar_url)
embed2.add_field(name = "Prize", value=f"{prize}")
embed2.set_footer(text="Giveaway Ended!")
server = ctx.guild.name
await ctx.send(embed = embed2)
await winner.send(f"You Won a giveaway in {server} \n Prize: {prize}")
``` code
nah i can change it but i need help
I am free, what's your issue
I did react to the message
I'm influential π
Can you scroll up and see
async def setup_db() i know some stuff xd
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
which lib are you using??
you dont need to commit to the db after selecting, you dont specify types while inserting, you are already getting the record on line 7 and you are fetching the records again
@slate swan add_reaction doesn't return anything
what is this
I want to cry now
:tada_cyan:
can i use this code:)?
Hi peeps do you know how to have this bot give out auto assign multiple roles members to when they join? in this code https://paste.pythondiscord.com/imiboqecin
@vale wing
it's not going to work if you just copy-paste it in
Then what should I use?
im working on this system for 2 days now
library like discord.py or pycord
Perhaps you mean this
roles = [some_list_of_roles]
await member.add_roles(*roles)```
dont-
To add reaction to the message and then get one user out of it
And mention him/her
okay
hi guys, what is this?
what is this???
yes
Well sorry I haven't worked with reactions for a while
its a Modal UI
and what is this
a command
postgresπ₯² its way simpler
ty sir
a event
?
Yeah am trying to add muiltple roles to the user when _member_join
welcome
no?
no?
they're both using SQL queries
u can create roles when user joins then use addroles
That thing will work
there's not really a difference in terms of querying and stuff,
making a connection in sqlite3 is eaiser too
[EDIT: only works with dpy2.0] u can setup connection like this b4 starting your bot
async with bot:
async with aiosqlite.connect(db-name) as db:
bot.db = db
await bot.start(token)
this will make it so that u dont have to connect again and again to the same db
what is this???
Asyncpg is much better than aiosqlite in terms of records fetching
You can change cursor factory ofc but still aiosqlite looks cringe
what do this command?
Error*
we were talking about ease, not productivity or whats better 
It is easier
error?
Where to add that?
Working with tuples is very inconvenient
its more readble
Dict-like objects are much more convenient
Cursor factory for aiosqlite can do that as well but yeah
Then what should I use?
Yes
ποΈββοΈ i just covert my tuple to a dataclass so really doesn't bother me
!d discord.Message.reactions prob (I haven't worked with reactions for a while as I said)
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
what i should to do if i want use this code?
write it yourself
guys?
what?
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
you need to fetch the message again before checking the reactions you added to it
async def setup_db():
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("CREATE TABLE IF NOT EXISTS wm(guild_id INTEGER, channel_id INTEGER, welcome TEXT, leave TEXT)")
await db.commit()``` would this work
thats my one connection
there's no point
then can u help me please because i dont understand now
how would you even run the function, and you aren't returning the cursor
so it will just return None
and I still recommend to switch to v2 since you just started with this bot and there's still time
well can u help me with my thing or nah
if i input rpm eat steak 4
rpm is prefix
eat is the command
steak, 4 is argument
how do i split steak and 4
just take them as arguments like eat(ctx, food_item: str, quantity: int)
or u can str.split
I could but there's no point....
i dont know, im out
^
@warped mirage u will still have to switch to 2.0 in a few weeks since the API version 1.7 uses will be decommissioned
And rewriting in a few weeks is not better than writing with 2.0 once
Alright letβs make a deal
If I update to 2.0 will u help me with the entire code
Idk

Hunter will
I mean, she (or anyone else here) isn't liable to help you here and she's making u switch to 2.0 since that will make sure yr bot continues working even when the current API version is decommissioned
Nice
what do this command?
@slate swan how do I install 2.0
i use repl it for coding
Lmao
is this good?
π€£
pip install git+https://github.com/Rapptz/discord.py
pip install -U git+https://github.com/Rapptz/discord.py
pip install (the thing u want)
oo he wants wrapper
wait do i gotta install git the software aswell?
ohmi god
how do i check if there is items in a dict? i know its simple but im having a mental blank. i want it to work that if there is items in a 'chest' certain text is printed, if all values are 0 (false) then return different text
Successfully built discord.py
Installing collected packages: discord.py
Attempting uninstall: discord.py
Found existing installation: discord.py 1.7.3
Uninstalling discord.py-1.7.3:
Successfully uninstalled discord.py-1.7.3
Successfully installed discord.py-2.0.0a4308+gf24f34e3``` is this correct?
yes
time to re-write with good code
first error
File "C:\Users\Dom\Desktop\beta test\bot.py", line 4, in <module>
from discord_slash import SlashCommand```
mportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)```
Yes
Uninstall those libraries
discord.py supports slash commands and other context commands
aiohttp 3.7.4.post0
aiosignal 1.2.0
aiosqlite 0.17.0
arrow 1.2.2
async-timeout 3.0.1
asyncio 3.4.3
attrs 21.4.0
binaryornot 0.4.4
certifi 2021.10.8
cffi 1.15.0
chardet 4.0.0
charset-normalizer 2.0.12
click 8.1.2
colorama 0.4.4
cookiecutter 1.7.3
cookiejar 0.0.3
discord 1.7.3
discord.py 2.0.0a4308+gf24f34e3
discord-py-slash-command 3.0.3
discord-ui 5.1.6
distlib 0.3.4
dnspython 2.2.1
easy-pil 0.1.6
filelock 3.6.0
frozenlist 1.3.0
idna 3.3
Jinja2 3.1.1
jinja2-time 0.2.0
MarkupSafe 2.1.1
mkdir 2020.12.3
multidict 6.0.2
pager 3.3
Pillow 8.4.0
pip 21.2.4
platformdirs 2.5.2
poyo 0.5.0
pycparser 2.21
pymongo 4.1.1
PyNaCl 1.5.0
python-dateutil 2.8.2
python-slugify 6.1.1
requests 2.27.1
setuptools 58.1.0
six 1.16.0
text-unidecode 1.3
typing_extensions 4.1.1
urllib3 1.26.9
useragent 0.1.1
values 2020.12.3
view 0.1
virtualenv 20.14.1
wavelink 1.2.4
write 2020.12.3
yarl 1.7.2``` what shall i uninstall
i have some xd
discord-py-slash-command
discord-py-ui
ok
And discord too
Not discord.py but discord
And why tf did u install asyncio via pypi
ok done
!pypi asyncio
ok ima uninstall
Yes
done
Python 3.10.2
Guys i am getting error can anyone help me fix?
my py version is Python 3.10.2 @maiden fable
u use repl it too?
Ye
Android
i'm on pc
Ok
i'm making my first bot
can i show my code?
i'm speak russian
#ΠΈΠΌΠΏΠΎΡΡΡ from
from webserver import keep_alive
from discord.ext import commands, tasks
from discord.utils import get
from discord.ext.commands import has_permissions, CheckFailure, check
#ΠΈΠΌΠΏΠΎΡΡΡ
import random
import os
import discord
import asyncio
import time
import discord.ext
#Π½Π°ΡΡΡΠΎΠΉΠΊΠ° Π±ΠΎΡΠ°
prefix = 'o!'
bot = commands.Bot(command_prefix = prefix)
bot.remove_command('help')
#ΠΊΠΎΠΌΠ°Π½Π΄Ρ Π΄Π»Ρ Π±ΠΎΡΠ°
@bot.command()
async def ping(ctx):
await ctx.send('pong!')
@bot.command(pass_context=False)
async def botping(ctx):
#ΠΡΠ²ΠΎΠ΄ Π·Π°Π΄Π΅ΡΠΆΠΊΠΈ Π² ΡΠ°Ρ
await ctx.send('ΠΠΈΠ½Π³: {0}'.format(bot.latency))
#ΠΎΡΠΎΠ±ΡΠ°ΠΆΠ°Π΅Ρ Π² ΠΊΠΎΠ½ΡΠΎΠ»ΠΈ ΡΡΠΎ Π²ΠΊΠ»ΡΡΡΠ½
@bot.event
async def on_ready():
print("bot online")
keep_alive()
bot.run(os.getenv("DISCORD_TOKEN"))
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "ΠΠΎΠ½ΠΈΡΠΎΡ Π°ΠΊΡΠΈΠ²Π΅Π½."
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
@bot.command(pass_context=False) ?
what's stopping you from making one?
Oh cool, was wondering since u have asyncio installed manually and it was meant for Python 3.5
when i make help command it doesn't works
do you get an error?
still doesnt work
and make screenshot
so when you put something like this in your code
@bot.command()
async def help(ctx):
await ctx.send("Help arrived!")
and you type o!help in discord, nothing happens?
now it works
nice
I tried looking for it in the documentation but I didn't have any luck finding out how to make the bot execute a certain block of code when replied to. Does anyone know?
!d discord.ext.commands.Bot.wait_for you mean this?
i tryed to make embed what send bot when i use o!help
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
how to make help menu in embed?
https://python.plainenglish.io/send-an-embed-with-a-discord-bot-in-python-61d34c711046 I think this is a great tutorial for embeds in dpy
Upgrade your botβs messages and make them a little more custom using embeds!
ok
You'd have to study how to make embeds.
Pls help me how to fix it
Lemme check.
there are examples on the docs for bot.wait_for
i dont know how to fix it(
code please
Ok
I mean, if someone replied to the bot just like what I am doing to you right now, it'd execute stuff.
seems like something you'd ask in #python-discussion
import discord
from discord.ext import commands
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
class channel(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def info(ctx, user: discord.Member):
img = Image.open("infoimgimg.png") #Replace infoimgimg.png with your background image.
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("Modern_Sans_Light.otf", 100) #Make sure you insert a valid font from your folder.
fontbig = ImageFont.truetype("Fitamint Script.ttf", 400) #Make sure you insert a valid font from your folder.
# (x,y)::β β β (text)::β β (r,g,b)::β β β
draw.text((200, 0), "Information:", (255, 255, 255), font=fontbig) #draws Information
draw.text((50, 500), "Username: {}".format(user.name), (255, 255, 255), font=font) #draws the Username of the user
draw.text((50, 700), "ID: {}".format(user.id), (255, 255, 255), font=font) #draws the user ID
draw.text((50, 900), "User Status:{}".format(user.status), (255, 255, 255), font=font) #draws the user status
draw.text((50, 1100), "Account created: {}".format(user.created_at), (255, 255, 255), font=font) #When the account was created
draw.text((50, 1300), "Nickname:{}".format(user.display_name), (255, 255, 255), font=font) # Nickname of the user
draw.text((50, 1500), "Users' Top Role:{}".format(user.top_role), (255, 255, 255), font=font) #draws the top rome
draw.text((50, 1700), "User Joined:{}".format(user.joined_at), (255, 255, 255), font=font) #draws info about when the user joined
img.save('infoimg2.png') #Change infoimg2.png if needed.
await ctx.send(file=discord.File("infoimg2.png"))
async def setup(bot):
await bot.add_cog(channel(bot))
@heady sluice
I'm thinking it's an event but I didn't find anything.
right, bot.wait_for() waits till something happens that it's waiting for
yes
It is in my bot....
you forgot self
Oof
every function in a class takes self as first param
you'll get used to them π
well I know and I still think it's a python issue rather than a discord.py issue, but send code then
or a quick google
def pingg():
return int(bot.latency*1000)β
yeah dpy returns NaN latency if you try to check it before the bot has actually connected to discord
oh
when do you execute this?
I am really confused ππ
based on their traceback they ran the function at the module-level
I need latency .... i tried to make a variable, but not working
okay but when do you call pingg()
A sec
you'd have to call it in a command
or on_ready
or a task that's waiting till it's ready
async def pingg():
return int(bot.latency*1000)β```
no...
you don't need an async function
for a function that doesn't have any asyncio in it
what is this???
Hmmmmm
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
Um are you even allowed to use those symbols in variables names
I usually don't recommend doing things in on_ready, but as long as you don't send a message or make an API call it's fine
u can make shorter this part of code
it's python
any unicode thing works
from PIL import Image, ImageFont, ImageDraw
PIL
For manuplating images
unicode
π©
from PIL import Image, ImageFont, ImageDraw
guys
I will try smthng rn, i hope it works
what
Guys anyone know a cool library that i can use in my discord bot?
so i updated to 2.0 , my py v is Python 3.10.2 what now
Pretty sure it's recommended to use english in your code tho
someone help me
what is this
bad code
thought it was a command
@slate swan wanna help me while hunter is afk
yeah
Can we add borders to image in pillow?
def pingg():
return int(bot.latency*1000)
but you don't return in a command
pretty sure yes
is this a command?
I'll add it then
No it is a simple function
can someone who has 2.0 of dpy help me please
Commands callbacks have corresponding decorators
what this function do?
return int(bot.latency*1000)
Returns bot's latency multiplied by 1000 with removed float part
you didn't tell what the problem is
can i use this?
i was told to uninstall discord , slash commands and ye my py version is Python 3.10.2
Why is it pingg and not ping tho
why would you uninstall discord
pip uninstall discord
And yeah why use function for such a simple calculation
why
Flooding namespace
hunter told me to
i dont know : D
For what
for my discord bot
Wtf discord
Yeah sure but it is not good. Do you want to make a ping command?
pip install -U git+https://github.com/Rapptz/discord.py to install 2.0
I copied this from a message where Ashley told u how to install 2.0
yes i did this
i already made
what happened then?
Ah okay then, you can exactly use
i had to uninstall discord , slash commands
i made this:
I don't think you had to
@bot.command()
async def ping(ctx):
await ctx.send('pong!')
and this:
@bot.command(pass_context=False)
async def botping(ctx):
#ΠΡΠ²ΠΎΠ΄ Π·Π°Π΄Π΅ΡΠΆΠΊΠΈ Π² ΡΠ°Ρ
await ctx.send('ΠΠΈΠ½Π³: {0}'.format(bot.latency))
remove pass_context=False already
why
cuz it makes no sense
ok
Why str.format like f-strings exist
and f-strings are great
await ctx.send(f'ΠΠΈΠ½Π³: {bot.latency}')
Yes + it's deprecated + why tf is it False but there's actually ctx arg
?
why does he have to uninstall discord
What's in it lol
i speak russian
lmao
Cz he doesn't need discord but discord.py?
you slavic?
Russian
well I made sure I don't sound american
Lol ok
That's not discord π€£
makes sense
The profile picture
Tbh won't be surprised if ppl fall for it
Well actually it is
you can send e-mails from others' mails
Really?
Maybe with unprotected protocol you can
Ok comrade

this is why we have DMARC/DKIM/SPF
@vale wing ΠΊΠ°ΠΊ ΡΠ΄Π΅Π»Π°ΡΡ ΡΠ°ΠΊ ΡΡΠΎΠ±Ρ Π±ΠΎΡ ΠΏΠΈΡΠ°Π» ΡΠ²ΠΎΠΉ ΠΏΠΈΠ½Π³?
Go to my DMs cuz speaking foreign languages is prohibited here
ok
Hi peeps do you know how to have this bot give out auto assign multiple roles members to when they join? in this code https://mystb.in/RanConfiguringSacramento.python
you do get that... even for mentions...
Guys how can we make that
If there is small price of image provided in a image ( short form:image recognisation) then bot should send message
Which library should i use?
Huh? No?
how to make it so that when you write a command o!myping he writes my ping
o! @carmine hearth
like this?
u write o!myping
then bot pings u?
yes
i did it it got approved now disnake documentation can be viewed offline and downloaded ^w^
not sure tho
u try
ok
any source?
alright thanksss
mention
btw that wont help fix my situation tho
its also something like normal commands without cogs
its still gonna end up 2000 lines
its hard to edit sometimes
i want to decrease the line of my main.py
when i write o!ping bot say pong!
...
it's a test command
@bot.command(name='ping')
async def ping(ctx):
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms"
here is the whole goddamn command for u
π€£
@bot.command()
async def ping(ctx):
await ctx.send('pong!')
... jesus christ
what
i wanna do something like
from Ping import ping
from Hunt import hunt
@bot.command(name='ping')
async ping(ctx)
@bot.command(name='hunt')
async hunt(ctx)
will this work?
def π
what's this
so i dont need cogs to do that =.=
go back to ur ping pong π€£
alright π€£
i will wait for ashley sarth and hunter to help me
cuz i dont understand the doc =.=
yes, thats when you don't use discord for a considerable amount of time and didn't sign off from notifications
you want to import commands from another file?
ya
cuz my main.py is getting too long
π
debugging on a 2k line file is starting to kill me
i dont even understand what is it talking about
#other.py
from discord.ext import commands
@commands.command()
async def foo(context):
...
#bot.py
from discord.ext import commands
from other import foo
bot = commands.Bot(**kwargs)
bot.add_command(foo)
bot.run()
``` π essentially what cogs do
π
cheh
what is this
but what is kwargs i see this thing a lot but idk what is that
what is this too
thats a commands.Bot subclass, very useful if you want to have custom methods and properties on your bot
i'll use it
commands.Bot(command_prefix="")
command_prefix here is a kwarg
@slate swan :white_check_mark: Your eval job has completed with return code 0.
{'hello': '1', 'world': '2'}
can i use this?
this is just a "not too good " way of adding commands which are in other files
cogs is the suggested way.
though, cogs do the same L.
out of interest,what's the point of having an init dunder which does nothing π. or did you just remove that part of the code
here's a noice example of how to make one with discord.py, make sure that you have the development version installed
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
oh, thought so
just send =.=
π
what development version?
Pip uninstall
rip
pip uninstall discord?
Yes
but why
if you were using discord-py-slash-comamnds, I'd do the same.
My py version is 3.10.2
what for
So what do I do now
And yes discord.py 1.7.3 has issues with building aiohttp wheels in py 3.10
So is it good that I changed
what did you change to
yes, thats better
and you would be using that in future anyways, so why not now
One question about dpy docs: I noticed that it is no longer /master/ in the URL but /latest/, did they make a release to pypi or smth
i was just about to ask where did the master branch go lol
A mirror package for discord.py. Please install that instead.
Oh ok
Ok cool
How do I import / download slash commands
Nvm it's the same
I have a question and it may be really dumb so I will say sorry in advance.
@bot.event
async def on_message(message):
if message.reference is not None:
da_msg = await fetch_message(message.reference.message_id)
if da_msg.author == bot.user:
message.channel.send("Someone replied to me?")β
```I'm trying to make the bot say something when a user references any of the bot's message but for some reason, my IDE says that fetch_message is not defined? I really don't know what to do now lol.
Your event loop is closed
Lul
Check ur code
here we go

Does this happen on bot shutdown
Guys when Iβm back can someone help me fix my code lol
is that your Full traceback?
Weird
don't tell me you're still stuck with that welcome thing
I think there should be another part
Sadly I am
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
It can't close just created loop if there are no errors
Ah yes
@slate swan man why would you put "my token" literally
You need to put your bot's token
i can write you a logic template but you need to code the queries and actions by your own
And for god's sake don't copypaste code if you do