#discord-bots
1 messages · Page 1136 of 1
@viral dock
oooh tnx
😋
So then the code is like this?:
#botcommand
#command Hello
@bot.command()
async def test(ctx):
await ctx.send("hello")
if message.content.startswith("*Hello"):
await message.channel.send('Hello!')
The cooldown decorators are meant to be applied to commands not buttons. You have to do your own implementation.
me trying to make a command?
Oh, is there any material on this topic?
Is RequestsWebhookAdapter this a thing on discord.py
Its not in the discord module as I see but idk they use it there
meaning its not now?
nope
what would be the alternative to it? wanna avoid creating a bot
🤔
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks") and [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
there is discord.webhook.async_.AsyncWebhookAdapter, its not meant to be used though
why its not meant to be used?
Yes it is?
nah thats different, you just want a webhook right?
for ...:
# inside for loop
# outside for loop
well, it's outside of the loop, right now, it should be:
for index, member in enumerate(role.members):
if foRole in member.roles:
fo = f"{member.mention} `{member}`"
elif hcRole in member.roles:
hc = f"{member.mention} `{member}`"
elif gmRole in member.roles:
gm = f"{member.mention} `{member}`"
inline=True
else:
memberList.append(f"`{member}`")
!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 want to send data through a webhook so that a message is posted in the channel where the webhook belongs to 😄
a webhook basically haha
discord.Webhook should be good enough then
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks") and [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
wait hol up how do u have that layout i just have the plain white and latest which one is that/
I want to make an asynchronous Python API Wrapper like Pycord/Nextcord/Discord.py etc as a side project
Can someone help me out on starting out and how to go abt understanding their masive number of github file names?
guys i need a bot to spam someones dms
wont help
can somene helppp 🥺
please i gotta troll my friend 🥺
help pls
just get the user obj and send the message smh
i want a bot to do it can u help 😭
multiple people
please
from discord.ext import commands, tasks
import discord
bot = commands.Bot(...)
@tasks.loop(...)
async def uwu():
await (bot.get_user(_id) or await bot.fetch_user(_id)).send(...)
uwu.start()
bot.run(...)
how to actuarraly use it in the bot and set commands? i know we have to go to the develepor page and stuff im there and i created a new bot
@slate swan
ik im dumb but why not use discord.Client here
'cause idc
can you help me with that
.
sorry i don't help in making spam bots.
😭
fair.
from discord.ext import commands
import discord
bot = commands.Bot(test_guilds=[your priv server])
@bot.slash_command()
async def dm(id: int, amt: int, *, msg: str):
user = bot.get_user(id) or await bot.fetch_user(id)
for _ in range(amt):
await user.send(msg)
bot.run(TOKEN)
you could
doesnt really matter that much
oh ok.
sarthak I wanna fork you and keep you with me forever 😔
do it before i archive myself like discord.py 
If you're in the discord.py server you can run the tag ?tag button cooldown and it will give you a pretty good description on how to do it.
Uh
i think interaction_check coro can be utilised for that
Can someone suggest me on how to go abt making a Python Discord Library?
import discord
from discord.ext import commands, tasks
bot = commands.Bot(command_prefix ='.', intent=discord.Intent.all())
@tasks.loop(seconds=1)
async def spam():
spamming =['enter ids here']
for i in spamming:
user= bot.get_user(i) or await bot.fetch_user(i)
user.send('spam')
@bot.event
async def on_ready():
spam.start()
bot.run('Token')
I don’t think so.
Cooldowns are separate from checks
im not talking about the decorator fyi
Idk then.
!d discord.ui.View.interaction_check this is triggered whenever someone interact's with this view's items
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
it's okay I'll stash you 😳
Oh. Thanks
found this guy who asked for a discord bot when i made it and hardworked he said no f u n word and then started being racist and swearing 😭 people wasting our time
i dont know why people like this exist
class MyView(discord.ui.View):
cooldown = False
async def interaction_check(self)-> bool:
if self.cooldown: return False
return True
@discord.ui.button(**kwargs)
async def callback(self, inter, button):
# do your stuff
self.cooldown = True
await asyncio.sleep(seconds to wait for)
self.cooldown = False
``` not the best way, but it works.
😔 sure, please do it
that’s definitely not the best way to do it
Plus they want a dynamic cooldown
Not a global cooldown
then I'll stash pop you whenever I want and get you back 😔
not the best way,
Yea, I was just adding on to what you said.
u can't ping it won't mention u can do role.mention tho
what if i decide to un-archive myself again just like discord.py
<@&id>
should work?
<@&ID>
ok
nvm just download ur code zip file
I'll push you to my own repo 😳
next level😳
😏 i still have my license in there
why you sound sus
!custom-cooldown forget this, use something like this.
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
doesnt work
doesnt work
it wont ping someone.
did you enter the correct ID?
where in embed are u trying this
field
name or value
name
you cant mention in names or title
^
what do i do then?
use the value
just use the name if you want to do display the role name in the field name
can i change the <@userid> in name then? so that it works
so many name
wont work
oof
ok
in value
field names and Embed title only support simple text and hyperlinking for the title
and emojis
embed.add_field(name='\u200b', value='<role>\nstuff')
important
the emoji thing has been added recently so yeah
how do you get member's avatar url in the new dpy
before it was member.avatar_url but idk now
avatar.url, alright thanks!
you can use emojis?
@commands.Cog.listener()
async def on_member_leave(self,member:nextcord.Member):
embed=nextcord.Embed(color=0xfd9fa1, description= f'{member.mention}{member.name}{member.discriminator}', title='Member Left')
if member.avatar is None:
embed.set_thumbnail(url=member.default_avatar,
icon_url=f'{member.default_avatar}')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
else:
embed.set_thumbnail(url=member.avatar.url)
embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
embed.timestamp=datetime.datetime.utcnow()
await self.bot.get_channel(933978399280599080).send(embed=embed)
this is my action log message for members leaving, but it wont send an embed or an error when someone leaves. does anyone know why?
on_member_remove @austere vale
yep,"remove" makes more sense because this event is also fired when a member is Kicked from the guild.
THIS WONT WORK FYI
how about no
if you stringyfy it
discord/asset.py lines 328 to 329
def __str__(self) -> str:
return self._url```
yea im putting it in an f string
how about yes
https://github.com/Rapptz/discord.py/blob/5de9287902ae3d4c1a9fc16ed6e7b3dcf204d6a0/discord/embeds.py#L398-L401 how about no again, set_thumbnail/image automatically stringyfies it
discord/embeds.py lines 398 to 401
else:
self._image = {
'url': str(url),
}```
ew
ofc, ew 😂
@client.command()
@commands.has_permissions(mute_members=True, administrator=True)
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
if handshake:
return await ctx.send(f"Successfully timed out {member.display_name} for {until} minutes.")
await ctx.send("**ERROR**")
await ctx.send("Something went wrong")
await ctx.send("Attempting to find the issue...")
time.sleep(5)
await ctx.send("Issue Found!")
await ctx.send("Incorrect Usage! Usage: t!timeout @person#0000 1h/hour")```
thats how every library does it anyways, they are converting it for the payload to send on discord
it works but u need mute_members AND administrator
mute_members is not a permission
oh lmao
I saw it in the discord role area
where u give perms to a role
discord.py 1.7.3 didn't implement that, that has been added recently
and its Manage Members iirc
*Timeout Members.
moderate*
what?
!d discord.Permissions.mute_members
Returns True if a user can mute other users.
for voice channels
thats only for discord.py, on the User Client its Timeout Members 🧠
F didn't think about that cause not related
it is what it is
no
😔 if i were referring to the dpy perm i would have said timeout_member
~~ idky its not in UPPERCASE but ok~~ they are all @quaint stream_values
nice
people with unfortunate names 😔
that's not even a thing
i mean yeah
nice ping
they didnt get a ping
@client.command(aliases=['banuser'])
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason= "No reason was provided"):
member_name, member_disc = member.split('#')
await ctx.send(":white_check_mark:", member_name + member_disc + "Banned them from the server")
await member.ban(reason=reason)```
it doesnt do anything, no errors, no nothing
await ctx.send(":white_check_mark:", member_name + member_disc + "Banned them from the server")
that works for print not ctx.send, use f-strings
await ctx.send(f":white_check_mark: {member_name}{member_disc}Banned them from the server")
{member_name}#{member_disc}
or simply {member}
they didnt have the # so didnt put it
for member in guild.members:
AttributeError: 'NoneType' object has no attribute 'members'
help
help
show where you defined guild
because in this context guild is None
guild = bot.get_guild(921366728016011324)
in a task
show the full task
it might be an issue with your scope
i gotta see it first though
tinv = 0
@tasks.loop(seconds=50)
async def inv():
global tinv
guild = bot.get_guild(921366728016011324)
for member in guild.members:
print(member)
for i in await guild.invites():
print(i)
if i.inviter == member:
tinv += i.uses
else:
continue
here
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
what
iirc it can return None if the guild is not in the bots cache
add await bot.wait_until_ready() in the first line of the function's code
smh i forgor
i haven't worked with dpy for a few months now
it worked
i dont even use dpy 
how many people can i role at one time?
?
hikari ftw
you mean how many people you can add roles to at once?
ah ok, should i add a wait time
yup
sarth - what was the limit of requests/minute for adding roles to members with the api?
its dynamic, there's no fixed ratelimit for that
but yes you should be able to add roles to 15 people in 2-3 seconds
@bot.command()
@commands.has_role("Phase 3")
async def addrole(ctx, role: discord.Role, members: commands.Greedy[discord.Member]):
#async def addrole(ctx, role: discord.Role, *members: discord.Member:
for member in members:
if role in member.roles:
await ctx.send(f"<@{member.id}> already in {role}")
else:
await member.add_roles(role)
await ctx.send(f"{role} added to <@{member.id}>")
just asyncio.sleep for 0.2 - 0.5 seconds before adding a role
# Запуск бота
@commands.Cog.listener()
async def on_ready(self):
cursor.execute("""CREATE TABLE IF NOT EXISTS users(
id INT,
name TEXT,
gems BIGINT,
iron BIGINT,
wood BIGINT,
organic BIGINT,
detals BIGINT,
batteries BIGINT,
fragments BIGINT,
work TEXT,
job_title TEXT,
experience INT,
Tool TEXT,
user_level_chat BIGINT,
user_xp_chat BIGINT
)""")
cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
id INT,
name TEXT,
work_1 INT,
work_2 INT
)""")
for guild in self.client.guilds:
for member in guild.members:
if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (f'{member.id}', f'{member}', 0, 0, 0, 0, 0, 0, 0, 'None', 'Безработный', 0, 'Руки', 1, 0))
cursor.execute("INSERT INTO cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', 1, 1))
else:
pass
conn.commit()
print("READY!")
Dear prompt why only 1 table?
which table got created?
users
cooldown is not created for some reason
you use CREATE TABLE IF NOT EXISTS, maybe the table is already there?
@commands.command(name = "3")
async def comand_col(self, ctx):
data = cursor.execute(f"SELECT work_1 From cooldown WHERE id = {ctx.author.id}").fetchone()[0]
await ctx.send(f"{data}")
I previously deleted the database. and made a test command which gave an error. also opening the database itself did not find the second table
how many times can I change the role colour? I mean do I get ratelimited if I change it per minute
how would i make a welcome message embed? i have the json for the embed but idk how to put it into the code
!d discord.Embed.from_dict
classmethod from_dict(data)```
Converts a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") to a [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") provided it is in the format that Discord expects it to be in.
You can find out about this format in the [official Discord documentation](https://discord.com/developers/docs/resources/channel#embed-object).
hm, add some prints in the on_ready to see till what part does the code executes
i think you can, but changing it in like 10-15 mins would be more ideal imo.
@slate swanOh I got it. If a separate command to create tables that works!!! thanks for the help!!!
you forgot an f before the string
also that isn't an embed?
he wanted to make an embed with a dict and im pretty sure he just wanted to know which method he can use which sarth gave it to him
Ohh
Nice Itsuki Nakano pfp on your github
Okey so, I got this problems in my Visual Studio Code. I have all already installed.
https://cdn.discordapp.com/attachments/993606142372626482/993607735369285672/unknown.png
How did you install them
well,
I installed discord -> npm install discord.js
I installed requests -> python -m pip install requests
I installed discord.ext -> pip install discord.ext.context
and colorama nad httpx i dont remember
Why are you installing JS discord?
httpx -> pip install httpx
idk, im new to this
my friend said that i have to have discord.js to have the import discord
resolved
what language do you want to code in?
python ofc
then don't install discord.js
oh
well, hehe
okey thanks
this video teaches you how to install libraries
This video is a quick tutorial on how to import Python Libraries when using Visual Studio Code.
I had been trying to figure this out for myself but could not find good tutorials on the internet so thought I should make one. For the purpose of this video, we'll use matplotlib in python as an example.
Timestamps:
0:00 Introduction
0:25 Create an...
what are you doing stalking my github😏
😳 checking your projects?
😩
Is this mysql?
"cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwli
nk/?LinkID=135170."
idk, i downloaded the venv like he do but at the end i got errors but i get the venv?
is it something i should skip or is this a serious issue?
are you on a virtual machine or something?
ye, my pc
like a physical machine or no
ye
physical
I've never gotten that error before I've got no clue
could someone here help me? pls!!!
Did you install the libraries?
is there a limitation on creating a modal from a response to a modal
yeah
How?
^^
errhm? discord.js?
You need py -m pip install git+https://github.com/Rapptz/discord.py
Cloning https://github.com/Rapptz/discord.py to c:\users\kaspe\appdata\local\temp\pip-req-build-msunjqzb
ERROR: Error [WinError 2] Det går inte att hitta filen while executing command git version
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
how do I install "git"?
you put the wrong link
it should be this
and download it?
yes
okok brb
idk but just use that for now
okok
now u can run this
this again
So I'm trying to make a discord bot that when I write $doit it sends all the files in the image folder but I would like it to do it one by one
So basically make a for loop and send the images
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$doit'):
await message.channel.send(file=discord.File("./images/*"))
client.run("OT*****************************************")
did u select this option
you can use os.listdir('./images') to get the names of all the files and loop through that
yes
thanks mate
but now how do I do the for loop
for filename in os.listdir(f'./images')
So I'm trying to declare my clients owner_ids like thispy client.owner_ids = owner_id for owner_id in client.config.owners.strip().split(",") if client.config.owners is not None else []but I'm getting a owner_id is not defined error, can someone help me figure out why?
hmm im not sure then
fakk...
maybe someone else will come along and know
i hope so...
it works
sounds nice
thank you so much 🙂
i dont think you can combine the if and for like that
try just making the if statement multiple lines
?
now you should be able to import it
omg now its resolved
import discord
👍
this is what I was going for, and it workspy client.owner_ids = [owner_id for owner_id in client.config.owners.strip().split(",")]
yep that would work
httpx and requests may need to be installed
im pretty sure the rest are built in
then try and and see if it works
^^
ye
@torn sail I have a weird error
Hey @vague cedar!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
commands.Bot
?
not discord.Bot
@vague cedarthere is a pin in this channel to help you resolve that. it was a massive bug for a while.
you need to change discord.Bot to commands.BOt
what pinned channel?
ye i got it
but get more errors
#discord-bots message you should find it here @vague cedar
def get_cookies(s, url):
try:
cookieinfo = s.get(url, timeout=5).cookies
dcf = str(cookieinfo).split('__dcfduid=')[1].split(' ')[0]
sdc = str(cookieinfo).split('__sdcfduid=')[1].split(' ')[0]
return dcf, sdc
except:
return "", ""
im trying to make it so i get a msg in the py file when someone joins the server the bot is in but it doesnt seem to work
@client.command()
async def devs(ctx, author):
if author.id == "625025751413948436":
await ctx.send("oh, hello there master")
embed=discord.Embed(title="Developers", description="Timmy Developers", color=0x0400ff)
embed.add_field(name="Developers", value="Clicks#8882", inline=True)
embed.add_field(name="Lead Developers", value="Clicks#8882", inline=True)
embed.add_field(name="Helpers", value="All the people over at the Pythone discord, they are amazing and very helpful. Join their discord if you ever need any help. join at ___", inline=True)
embed.set_footer(text="Want to be a developer? Join the development discord server and ask! t!discord • Updated on 2022/07/04")
await ctx.send(embed=embed)```
no output
nothing. no error message, no embed sent, no message sent
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
need to see more of the error
did i do it wrong? i added the stuff thats underlined
that still didnt seem to work :(
did u enable it in the dev portal
yeah
@client.command()
async def devs(ctx, author):
if author.id == "625025751413948436":
await ctx.send("oh, hello there master")
embed=discord.Embed(title="Developers", description="Timmy Developers", color=0x0400ff)
embed.add_field(name="Developers", value="Clicks#8882", inline=True)
embed.add_field(name="Lead Developers", value="Clicks#8882", inline=True)
embed.add_field(name="Helpers", value="All the people over at the Pythone discord, they are amazing and very helpful. Join their discord if you ever need any help. join at ___", inline=True)
embed.set_footer(text="Want to be a developer? Join the development discord server and ask! t!discord • Updated on 2022/07/04")
await ctx.send(embed=embed)```
any1 knows what it means when writing (embed=embed) to create an embed
I know what is its use
but idk how it works
Arguments can be passed based on their position or using a keyword.
In this case, send() has defined the embed argument to be keyword-only. This means it cannot be passed just based on its position.
Hence, embed= is needed in front (embed is the keyword)
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
thanks!
the intended use of this command is !devs @user correct?
that usage doesn't really make much sense when you consider what the command does.
I would suggest removing the function argument author and then to check whether or not your command was run by you, use ctx.author
^^
It’s meant that if I do the command it will say "hello master" and if it’s some other dude it will list the devs
You got an on_message event?
for?
No I'm asking if you have one in your code.
Why are you making author a required argument?
if I am the one who executed the message it will say hello master, otherwise it will send the embed
I recommend remove the argument author then use ctx.author.id instead of author.id and replace await ctx.send("oh, hello there master") with return await ctx.send("oh, hello there master")
mk
Since you are working in a function return is used so you can stop the function from going further.
I got bored so I did it
Had to stay within 5 message edits / 2 seconds though
ratelimits go brrrrr
its a private bot right?
yeah
still nice for 4-5 players at a time in channel
because making games concurrently would easily get ratelimited
ANSI finally utilised well
it's alright to set a max concurrency for the command
the ANSI looks great unless you're on mobile
show it
indeed
ansi on phone is cursed
even per guild it wouldnt matter
if you have the game on 2 guilds your bot would easily get ratelimited
;-;
🗿
my eyes
mobile client is just horrible smh
truly
better rendering
more
I wonder, since I'm using the interaction token to edit the message, is the ratelimit per-interaction?
Can't possibly be
The ratelimit bucket will be per token
As it's using a webhook really, which is one of the major params when determining buckets
they couldn't get more widely used langauges like cpp to render on phone, ansi ...
I've seen only python, javascript & rust codeblocks on phone yet
damn
any reason why?
I have seen codeblocks, but no code formatting on phone 💀
not that im aware of, maybe they would release a "buy nitro to use x language codeblocks" on phone
you mean syntax highlighting?
await was used outside accoroutine, move it inside an async function
Why is it in the global scope
Put it into a function
When did you want it to send, that's what you should ask yourself
Alright, so it looks like the ratelimit is per-interaction
So i can have as many of these going as i want supposedly
My phone doesn't even render those correctly lmao
you won't find much difference even if it did 🗿 they all appear same
wouldnt doubt it
so per button in this case?
ah, what about the buttons in the embed?
you can interact with the button without caring about ratelimits?
I mean, the buttons do have their own cooldown
dont buttons have ratelimits
i'm pretty sure there should be some ratelimit for editing the message tho cause they are literally just webhook messages
you can't click them too fast, but the message edit ratelimits are per interaction, and I just use the slash command's interaction token
They don't have ratelimits... that the bots have to care about. See it like reactions, if you spam reaction on a message the user gets rate limited by Discord.
how would one go about formatting an output from a sqlite3 db? This is what I see currently
oh yeah that makes sense, it takes upto 0.2 seconds to send the interaction itself
mhmmm so in theory you can have many games running concurrently
could you elaborate wym by formatting, a table?
just cleaning the text up so it looks nicer
a dataclass or a parser function would be good
well its a list of tuples,
you can use .join maybe
Most likely not since an embed edit does contribute to the ratelimit since it's not a response.
I'm at a very basic level here :p like, learning to crawl basic level haha
right i forgor
oh
It does, but like I said, it seems to be per-interaction
!join read this
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
I think it's highly unlikely you won't get rate limited when running that concurrently. That is if you want your bot not to break several ToS rules.
Haven't gotten ratelimited yet, so
On how many instances of the game?
so currently the code I have is
with conn:
cur.execute(f"SELECT seriesName from sonarr WHERE discord_ID=?", [id])
return cur.fetchall()
def results(ctx):
discord_user = get_create_user(ctx.author)
return get_user_subscriptions(ctx, discord_user[0])```
I did two, which was about 4 updates / second. The ratelimit header said 5 per 2, and the remaining never dropped below 4
when I tried to add (separator.join( before the (ctx etc in the last line, it threw an error in vsc saying the first ( wasn't closed?
I'm gonna test it on a few more at a time, see what I get
you can have something like this
!e
print(" ".join(map(str, sum([(1, 2) , (3, 4)], ()))))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1 2 3 4
!e ```py
a = [("apple",), ("banana",)]
print("\n".join(i[0] for i in a))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | apple
002 | banana
better ;-;
yeah that second option would work nicely
- readable
!e ```py
print(*map(str, sum([(1, 2) , (3, 4)], ())))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
1 2 3 4
here we go
so how does that work with a return function?
depends on what he wants
we gave him ideas ig
well apparently, the results() is returning the the screenshot you sent right?
consider a to be the return value of results
another sidenote: since you're in an async environment, aiosqlite would be a better choice.
!pip aiosqlite basically sqlite3 with async/await syntax
correct
how will that change what is required in the code?
16 games running concurrently, and haven't been ratelimited yet
https://gist.github.com/matthewzring/9f7bbfd102003963f9be7dbcf7d40e51#syntax-highlighting
it's coloured to match python formatting
you can see the examples on their documentation, you just need to add some awaits, thats all
ah k will have a look, cheers
When does an embed get updated?
It's being updated using the slash commands interaction token every second or so
using this endpoint
https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
is hikari good?
i guess it will
@commands.Cog.listener()
async def on_member_ban(self,member:nextcord.Member):
embed=nextcord.Embed(color=0xfd9fa1, description= f'{member.mention}{member.name}{member.discriminator}', title='Member Banned')
if member.avatar is None:
embed.set_thumbnail(url=f'{member.default_avatar}')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
else:
embed.set_thumbnail(url=f'{member.avatar.url}')
embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
embed.timestamp=datetime.datetime.utcnow()
await
does anyone know how to fix this?
can you send what command you are trying to run
oh wait im dumb its an event mb
oh its just an audit log embed for banning
and when i banned someone it sent the error and didnt send the embed
read the docs, it needs a guild arg as well as a user arg
!d discord.on_member_ban
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
better than dpy and its forks.
dpy ew gives me a stroke
the naming conventions
thats majorly subjective imo. they would have to use both to see which ones better because whats better is what they think of the library
neither are bad or anything but what makes it good is how you like the library
the library that I use is the best and all the others are the worst
oh hell yeah i can get around thet statement 
I think you guys haven't seen the paragraphs sarth has posted on why hikari is better than dpy.
the 3 statements arent written by him ofc, but iirc this is one of the paragraphs
i haven’t because im barely ever active in this server and quite frankly, i dont care that they’ve written paragraphs on it lollll
if i like a library and it’s my perference, then it’s my preference and noting will change that. so someone writing paragraphs on a subjective subject is stupid
(which is a bit ironic since thatd what im doing)
i think were talking about lib abstractions and not personal preference
i think he aimed the statement on performance and and implementation of the dpy project
some people like the commands structure ofc but some people implemented the same thing but better, i think thats his point, the impl of some features. it would be cool to see a full dpy rewrite and see all the old codebase be replaced with a new one
ofcourse its personal opinion
just to be clear i was talking about the codebase and extendability.
what is the function to get a list of cog objects
!d discord.ext.commands.Bot.cogs
property cogs```
A read-only mapping of cog name to cog.
this only returns the names ig
that's the only way
create a list and a task and make it update a botvar every x time if you want it to or just do stuff in the setup_hook
i just found out some thing
it dosent return a list
it returns a dict
which maps name and object
it returns a MappingProxyType
iirc its a dict that isnt mutable
so it doesnt have __setattr__
lol
now time to grind and write help command help descriptions🥲
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=discord.Embed(description=f"🚫・{member.metion} You have no permissions to use this command"color=0xfe4343)
await ctx.send(embed=embed)
else:
raise error
embed=discord.Embed(description="🚫・{member.metion} You have no permissions to use this command"color=0xfe4343)
^
IndentationError: expected an indented block after 'if' statement on line 53
Does someone know what am i doing on this command?
when you dont do the documentation while writing the code
you forgot a comma
lazy i always leave best part for last
Oh god thx u i was trying everything
I filled the form for api acces but till now they have not sent me the api key on mail
can someone remind me how to make this function be called whilst the bot is running```py
class Timeouts(commands.Cog):
def init(self, bot):
self.bot =
async def get_timeouts(self):
...
hello guys how i can make a give role cmd !role @idk @role
as soon as the bot starts?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
do you load the cog when the bot starts running or before that?
how i can do something it says role gived to that person
!d discord.ext.commands.Cog.cog_load use this with Bot.wait_until_ready
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
i was actually looking for something like bot.loop.create_task(I think?)
does this work?
@bot.command()
async def give_role(ctx, member: discord.Member, role: discord.Role) -> None:
await member.add_roles(role)
await ctx.send('added role :thumbsup:')
that would work as well, but remember that it won't return an value and won't wait for the function to get fully executed before executing the next line
How we can make a running text comamnd? Like it's on the screens
Like >runningtext <text here>
Which makes the text running from left to right in the embed
make a gif which has the text running across it, then send it in the embed?
Not like it's on the screens
Not image
Like it edits the messega every 1 seconds
Like
hello world
D hello worl
ld hello wor
old hello wo
you will be rate limited
Hmmm
I am already rate limited
Replit makes rate limited
Is there any way to do with image?
^
But there no library to make gifs
https://note.nkmk.me/en/python-pillow-gif/
PIL supports it
How can I change the text?
image manipulation with dpy is a mess 😔
Like
hello
o hell
lo hel
llo he
ello h
hello
make multiple images with the different texts, then combine them into one gif
No not images
This
if you like getting ratelimited, then message.edit(new-message)
I mean that my bot automatically makes the text like this
How can I d it?
*message.edit
right, where was edit_message
?
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
ah yes
class MyBotEvent(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=ConfigurationData['command_prefix'],
intents = discord.Intents.all(),
application_id=ConfigurationData['ConfigurationID'])
self.individual_cogs_list = []
async def setup_hook(self):
for command_and_events_folder in os.listdir("./cogs"):
# Now we have a object for each folder
for individual_cog in os.listdir("./cogs/"+command_and_events_folder):
if individual_cog.endswith('.py'):
individual_cog = f"cogs.{command_and_events_folder}.{individual_cog}"
self.individual_cogs_list.append(individual_cog[:-3])
for cog_to_load in individual_cogs_list:
try:
await self.load_extension(cog_to_load)
print(f"[SYSTEM] {cog_to_load} Loaded")
except Exception as exception:
print(f"[SYSTEM] {cog_to_load}: {exception}")
await bot.tree.sync(guild=discord.Object(id=int(ConfigurationData['ServerGuildID'])))
I read 2.0 migration changes, and I updated my bot. But, it still won't seem to work. Can anyone help
i don't think so the tertis command didn't get rate limited this seems unlikely
Hmm
tell me about it 💀
nicely complicated code
honestly it will be easier with just text
hahaha, I used to make my code mad sloppy. Does it not look nice?
it gets unnecessarily complicated with images
very bad
How can I do it?
really? still readable?
overly complicated
seems pretty neat, but I may be wrong. Lmk how to clean
redundant
ouu tryina reduce that, where can I make changes
!e
string = 'hello world'
lst = [string[i:]+string[:i] for i in range(len(string))]
print('\n'.join(lst))
the part where you make the cogs list
@shrewd apex :white_check_mark: Your eval job has completed with return code 0.
001 | hello world
002 | ello worldh
003 | llo worldhe
004 | lo worldhel
005 | o worldhell
006 | worldhello
007 | worldhello
008 | orldhello w
009 | rldhello wo
010 | ldhello wor
011 | dhello worl
how could I fix that?
maybe combine the 2 statements
just load the cog instead of appending to list
regardless of redundancy rn. Is there anything WRONG
you could actually write whole of the loading part in just one line ngl
NO WAy
alr cool cool, ill ajust
do you get any errors?
no errors, it doesn't say anything
thanks for the challenge 😄
nope there isn't
I already have written it a lot of times in the channel
How can I make my bot edit it every 1 second?
its alr, ill do it again :)
Underneath that segment of code it says
BotEvent = MyBotEvent()
BotEvent.remove_command('help')
# Load global varibles to use in the cog files
BotEvent.ConfigurationData = ConfigurationData
# Edit data tiers in the bot
if not BotEvent.ConfigurationData["BotTier"] == "custom":
BotEvent.ConfigurationData["BotAccessModules"] = TierInfoData[BotEvent.ConfigurationData["BotTier"]]
# Create Cogs List to refer to
BotEvent.run(ConfigurationData['bot_token'])
for i in os.listdir('cogs'):
if '.py' in i:
await bot.load_extension(f'cogs.{i.replace(".py", "")'})
ew
ill change, but ima slice 😉
My school tommorow and my 1 holidays work not done 😨
yeah either
cool thank you!
i can do it in one line as Ashley said
[await self.load_extension(f"cogs.{file[:-3]}") for file in os.listdir("cogs/") if file.endswith(".py") and not file.startswith("_")]
easy peasy
but code needs to be readable
or sarth & black gonna kill me
it doesn't even error out
hm?
sad
it just sits there
😦
any issues?
add a print statement
I'm tryina use buttons and menus but they are only available for V2 rn IG. So I gotta redo my bot
to check
alr ill try! one sec
are u trying setup hook in 1.7.3?
anyone know why this is not getting all members who are on timeout? ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
for members in disnake.utils.as_chunks(guild.members, 10_000):
for mem in members:
if mem.current_timeout:
self.timed_out.append(mem)
await asyncio.sleep(0.3)
print('Completed getting timeouted members')
I would give u a gift if u make people in #esoteric-python, understand this
it's only showing one, but i'm sure there are more than one
add a print statement and check
where?
print mem
oh no
oh wait a sec
wait, am i just checking for the first 10,000 members?
y for members in guild.members
what do you mean?
wont guild.members return a list already
nope
huh?
i need the list of members who are on timeout
i'm calling the func by a cog_load
!d disnake.utils.as_chunks
disnake.utils.as_chunks(iterator, max_size)```
A helper function that collects an iterator into chunks of a given size.
New in version 2.0.
^
It's not good when the guild has 380,000 members and it takes 15 seconds or so
I initially tried that
Who black?
Well, then u can use a task
!pypi black
You mean python package?
or threading
the formatter yes
But why does the code error
U should use a print statement
I have one when the loops complete
do it in the loop we will know how many are timed out
or if the loop is even reaching there
Okay
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
property guilds: List[nextcord.guild.Guild]```
The guilds that the connected client is a member of.
no
I will start with hikari tommorow
replit dbs is slow ngl
does anyone have a bot that uses cogs, that they made in DPY 2.0
that I could take a look at
Does db["Guild"] returns a string?
sarth should get the gist pinged ngl
Can u print the type of that?
bro
I'm out
print type(db["Guild"])
pinned*
bro
at least correct my punctuation
that's basic python
and it's alot easier to help when u know atleast the basic python
replits db is like a dict so its just like regular indexing lol
no u use the print function
print(type(db["Guilds"]))
yeah so it's an int not string
I'm not sure what u were trying to do after this so I'll leave here lol
yeah no sorry idk a thing about slash commands
yes
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
i'm trying ;; help? idk what i have been doing wrong. it's for a discord music bot
someone told me to do a coroutine but i had no idea how to do it
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
so I have ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
for members in disnake.utils.as_chunks(guild.members, 10_000):
for mem in members:
if mem.current_timeout:
print(mem.name)
self.timed_out.append(mem)
await asyncio.sleep(0.3)
print('Completed getting timeouted members')
this prints
```py
๖ۣۣۜA̸ᴍeꪀør # Just some dumb name
Completed getting timeouted members
but there are more names it should print
maybe only person is timeouted
um....why are you overcomplicating that? if I may ask
you mean remove the chunks and just do a normal loop?
issues irl
mhm
yeah a simple list comp?
380000 is not much
not so much yeah
it took a long time with list comprehension for some reason
how much approx?
maybe latency
10-15 I think
or slow internet
min?
[*filter(lambda x: x.current_timeout, guild.members)]
well yeah...I did just only check it once
there shouldnt be much diff in perfomance
its actually faster than for loop ^
if its memory problem maybe its better to use generators
it should be significantly better then 10-15 seconds
yeah but barely
filter is implemented in c, so its going to faster
just use c to make bots ez
[*filter(lambda x: x.current_timeout, guild.members)] what is the return type of this?
list
so what's the * for?
unpackning filter object
map<<filter<=for
map is fastest
i can't use map here
filter or for will roughly be same
!e
a = filter(lambda x: x%2, range(10))
print(a)
print([*a])
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
001 | <filter object at 0x7f9baf765540>
002 | [1, 3, 5, 7, 9]
maybe it is, but it doesn't make sense here
its same as list(filter())
indeed
thanks. So this is correct? ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
members = [*filter(lambda x: x.current_timeout, guild.members)]
for member in members:
print(member.name)
self.timed_out.append(member)
but if for loop took 10 sec it wont magically become 2 or 3 with a filter
add a time.time and check the time it takes
just do
self.timed_out = [*filter(lambda x: x.current_timeout, guild.members)]
why are you appending?
they are also checking member.name but that can be done later by printing the complete list too
class Timeouts(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.timed_out = []
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
for members in disnake.utils.as_chunks(guild.members, 10_000):
for mem in members:
if mem.current_timeout:
print(mem.name)
self.timed_out.append(mem)
await asyncio.sleep(0.3)
print('Completed getting timeouted members. Bot is ready')
then later I am doing ```py
@commands.command()
@needed_check()
async def timeouts(self, ctx):
if not self.timed_out:
description = "No members are currently on timeout"
else:
description = "\n".join(
[
f"{member.mention} ({str(member)} is on timeout until <t:{int(member.current_timeout.timestamp())}>)"
for member in self.timed_out
]
)
embed = disnake.Embed(
title=f"Members on timeout ({len(self.timed_out)})", description=description
)
await ctx.send(embed=embed)
then just do self.timed_out.extend([*filter...])
oh okay
append would be very slow
^^
+= might also be faster
right
so += is faster than extend?
wont cause much diff
if u really wanna check then add time.time() and check for all combos like for loop filter and all
no I just didn't know what this was comparing
!timeit
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
@shrewd apex :white_check_mark: Your timeit job has completed with return code 0.
200000 loops, best of 5: 1.67 usec per loop
@spring flax whats the len of self.timed_out??
!timeit
a = [1,2,3]
a += [4,5,6]
print(a)
so - ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
self.timed_out.extend([*filter(lambda x: x.current_timeout, guild.members)])
print([member.name for member in self.timed_out])
print('Completed getting timeouted members. Bot is ready')
@shrewd apex :white_check_mark: Your timeit job has completed with return code 0.
200000 loops, best of 5: 1.67 usec per loop
its same
just printed one name
that means only one person is timed out ;-;
they left or timeout is over
you just want the names of the time outs?
@paper sluice this is what i am doing for the command
i'm looking at the audit logs right now and it's telling me there are more than one users on timeout
for what it's worth, https://paste.pythondiscord.com/metalimune
Metalimune seems like an interesting word
do you still have performance issues with that?
No, the only problem is that it's not showing all the members on timeout
nobody has solutions?
what is config['prefix']
and the intent is not defined?
:
How is the intent not defined?
wait the intent is alright
but what's that prefix
which lib?
pycord
did u run the bot?
Of course
do this
from discord.ext import commands
bot = commands.Bot(...)
@bot.command()
...
bot.run(...)
For some reason it is still not responding to the command :userinfo. commands from from discord.ext import commands is also not used.
The slash commands and the other events work perfectly fine, only the prefix commands don't seem to work for me.
because for prefix commands
u need commands.Bot
Thank you! That was the problem.
Man
what's wrong catto
Return and await commands are killing me
I just cant understand what’s the problem w it
Whenever i type return or await, it shows up as an error
u need help?
Rn, im on phone
If you want to help uh, could you wait for an hour?
I actually need help 😭
Hi guys, someone knows why am I receiving this when I try to conenct my bot (and they don't connect)
u spammed discord api with requests💀
💀
I mean... The previous bot never had this problem and I didn't particularily spam it x.x
I don't understand, what should I do now?
it doesn't ban for no reason, as it says you've been banned for temporarily try waiting a few hours
is ur bot too big or u have a very frequent task or something?
both lmao
I'm embarrassed...
it's been used by like 5 or 6 people simultaneously the whole time
thing is that when i connect the bot from my pc it works no problem, but from replit it annoys me with rate limit thingie
you are only getting timeouts from one guild right?
yes
the member that doesn't show up in the timeout list, check if they are in guild.members
i did
i looked at the audit logs. It showed definitely more than one, and I checked if those they were showing were in the mutual guilds and it showed, so they are in
did their timeout end?
no
manually check what member.current_timeout returns for that member(s)
okay
@client.command()
@commands.is_owner()
async def shutdown(ctx):
await ctx.respond('Shutting down.')
exit()```
It doesn't seem to do anything when I do .shutdown?
It's supposed to stop running the bot.
Well maybe doesn't work because I am hosting it on heroku - yeah..
can someone throw me to the documentation line where there is info for creating/adding custom emoji
ok i have 2 pieces of advise for u first stop using replit to host and two shard ur bot
Way to many mistakes on this
;-;
just scale down the dyno
but the error occured in that line
any changes there ?
Well i am on mobile rn so i cant possibly help
How?
@spare urchin i will sed when i would be free
anyone?
ok.
u are missing a )
u mean a closed parantheses for the one starting with (user??
ok..
i'll change host soon, what do u mean shard ur bot?
how do you add a custom emoji to your discord server
server settings -> emoji
using python dpy
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
You can always see the docs, they have good function namings
.
Hi
hi @.moderator
cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
id INT,
name TEXT,
work_1 INT,
work_2 INT
)""")
for guild in self.client.guilds:
for member in guild.members:
if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
cursor.execute("INSERT INTO cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', 1, 1))
else:
pass
conn.commit()
Dear, please tell me how to enter today's date in the value work _1
SQL has a column type date use that
@shrewd apex you told me to get the perspective api key but till now from yesterday they have not sent me email of key
hm? I'm not a moderator
i
?
do you guys know any free bot hosting websites?
you are, you just don't know it 😄
how can i put the code in a nice way like this😭
!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.
@commands.command(name = "BD2")
async def comand_BD2(self, ctx):
cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
id INT,
name TEXT,
work_1 timestamp,
work_2 int
)""")
for guild in self.client.guilds:
for member in guild.members:
if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
cursor.execute("INSERT INTO cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', joining_date, 1))
else:
pass
conn.commit()
await ctx.send("ДА")
Dear, I found material on the Internet about SQL date and time. but for some reason it didn't work for me. how to write down the date and time in the value please tell me.
import discord, random
TOKEN = 'can't show you token<3'
client = discord.Client()
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@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 == "testing-1":
if user_message.lower() == "hello":
await message.channel.send == (f'Hello {username} !')
client.run(TOKEN)
okay finally
tell me why my await and return doesn't function
it gives me an error
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
you forgot 'py' after the quotes!! this will make the text colored
what does that mean
i should type py after both quotes?
def function():
# inside function
# outside function
😨
only after the first
both if statements are outside the function
ik, i read both then looked at the function
Oh good 👍
thanks ryuga and sparky, im processing slowly ever since im learning to code
Just make more commands in discord.py it will help u learn python more
also use cogs
So it will increase ur oop skills
That's how I learned
add a emoji
Is there any simple function or command to hide cogs from the send_cog_help command
button = Button(emoji='', label='', style=discord.ButtonStyle.link, url=)
how long did it take you
Anyone know the issue?
indentation
still learning.
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
@sullen pewter im on a android i cant use indent here
4 spaces
import discord
import random
TOKEN = "can't show ya<3"
client = discord.Client()
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@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 == 'testing-1':
if user_message.lower() == "hello":
await message.channel.send == (f'Hello {username}!')
return
if user_message.lower() == "bye":
await message.channel.send == (f'See ya later {username}!')
return
client.run(TOKEN)
ok
i gave it a command to say hello and bye
its not responding tho
waste of my time smh
