#discord-bots
1 messages · Page 981 of 1
isn't this easier? authorized = [guild for guild in guilds if guild.permissions.manage_server]
token is literal to a command object and not a string
so str(token) should work?
but yd u said u use tabnine?
Actually next, but close enough
gotchcha
not really as making the command object a string returns its name i think i havent checked the dunder
i do react too so i might able to understand the code
And it’s not worth increasing bundle size by adding discord.js
tabnine has an extension for vsc too
I have some un pushed commits on my computer with the new code on it
yeah. if u use intellisense u can't use tabnine ryt?
Hi there, I made a command to be able to vote for a character every 24h using commands.Cooldown but if the name input isn't correct it sends an error message to the user. Now, the issue is that if you don't put a correct name you're still on cooldown for 24h, how can I fix it so you don't have to wait for that long ?
tabnine is used for intellisense. Period.
Hi
no prob just drop the code on dm when u r free
👋
the cooldown gets invoked when the context of the command is invoked no matter the result so i doubt you can
Pfp change again
then how can I declare the command cooldown inside the command in a if statement ?
by intellisense i meant the completion provided by vscode python extention made by microsoft
nah, you can use
you cant really its a deco that gets called when the callable gets called
declare a datetime.datetime.now() when the bot initialised
And subtraction it from another datetime.datetime.now() from it inside on_ready
And then how do I get the time it took to startup
I have used kite and that one. python extention had it better
Difference between them is the time difference....
and never thought kite was batter than tabnine cz kite's older
why would you even record the time your bot takes for it to populate its cache?
Then is there a way to not use a decorator and instead have an internal cooldown in the command ?
It would still need a cache/database
maybe editing internals and checking what the callable returns
!custom-cooldown maybe utilise 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.
You can just declare a variable with the current datetime at the start:
import datetime
StartTime = datetime.datetime.utcnow()
and then just declare another variable inside your command:
@bot.command()
async def test(ctx):
x = StartTime - datetime.datetime.utcnow()
await ctx.reply(x)
I need a moment to understand how that works
async def vote(self, ctx, *name):
""" Vote system for your favourite OCs"""
id = ctx.guild.id
name = " ".join(name)
cursor = self.db.cursor()
cursor.execute('SELECT DISTINCT oc_name FROM main WHERE guild_id = ?', (id,))
result = cursor.fetchall()
if name in result[0]:
cursor.close()
cursor = self.db.cursor()
cursor.execute('UPDATE main SET oc_rank = oc_rank + 1 WHERE guild_id = ? AND oc_name = ?',(id,name))
self.db.commit()
cursor.close()
await ctx.send('Thank you for your vote!')
else:
await ctx.send('Invalid name')
``` that's my code for the moment
So I could make message_cooldown_vote = commands.CooldownMapping.from_cooldown(1.0, 86400, commands.BucketType.user)
then bucket = message_cooldown_vote.get_bucket(message) retry_after = bucket.update_rate_limit()
(inside my command)
and put the retry_after in my if name in result
Hmm
right...?
Yo I m having some trouble sending an image in an embed. I am using igur. I can send one image but the second i change the URL to the image I want it doesn't send. could the image be too big for the embed and it can not minimize it?
Yikes
it works now lol
could you show the code and how you're changing it?
cursor.fetchall() works?
Turns out it was the size of the image, thank you though!
oh well, the better
i just asked
never wanted to give extra over-smartness
And I just told you that wasn't the issue but it felt like you thought it was a problem
I just asked it for my information, seems like im too drunk since im asking stuff i already know about lmao
lmao
@client.command()
@commands.has_permissions(administrator=True)
async def giveaway(ctx):
# Giveaway command requires the user to have permissions to function properly
# Stores the questions that the bot will ask the user to answer in the channel that the command was made
# Stores the answers for those questions in a different list
giveaway_questions = ['Which channel will I host the giveaway in?', 'What is the prize?',
'How long should the giveaway run for (in seconds)?', ]
giveaway_answers = []
# Checking to be sure the author is the one who answered and in which channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
# Askes the questions from the giveaway_questions list 1 by 1
# Times out if the host doesn't answer within 30 seconds
for question in giveaway_questions:
await ctx.send(question)
try:
message = await client.wait_for('message', timeout=30.0, check=check)
except asyncio.TimeoutError:
await ctx.send(
'You didn\'t answer in time. Please try again and be sure to send your answer within 30 seconds of the question.')
return
else:
giveaway_answers.append(message.content)
# Grabbing the channel id from the giveaway_questions list and formatting is properly
# Displays an exception message if the host fails to mention the channel correctly
try:
c_id = int(giveaway_answers[0][2:-1])
except:
await ctx.send(f'You failed to mention the channel correctly. Please do it like this: {ctx.channel.mention}')
return
# Storing the variables needed to run the rest of the commands
channel = client.get_channel(c_id)
prize = str(giveaway_answers[1])
time = int(giveaway_answers[2])
# Sends a message to let the host know that the giveaway was started properly
async def message(ctx, user:discord.Member, *, message=None):
await ctx.send(
f'The giveaway for {prize} will begin shortly.\nPlease direct your attention to {channel.mention}, this giveaway will end in { } seconds.')
# Giveaway embed message
give = discord.Embed(color=discord.Color.orange())
give.set_author(name=f'Giveaway!', icon_url='https://i.imgur.com/VaX0pfM.png')
give.add_field(name=f'Prize: {prize}!',
value=f'React with 🎉 to enter!\n Ends in {round(time / 60, 2)} minutes!', inline=False)
end = datetime.datetime.utcnow() + datetime.timedelta(seconds=time)
give.set_footer(text=f'Giveaway ends at {end} UTC!')
my_message = await channel.send(embed=give)
# Reacts to the message
await my_message.add_reaction("🎉")
await asyncio.sleep(time)
new_message = await channel.fetch_message(my_message.id)
# Picks a winner
users = [user for reactions in new_message.reactions
async for user in reactions.users()
if user != client.user]
winner = random.choice(users)
print(users)
# Announces the winner
winning_announcement = discord.Embed(color=discord.Color.orange())
winning_announcement.set_author(name=f'The Giveaway has ended!', icon_url='https://i.imgur.com/DDric14.png')
winning_announcement.add_field(name=f'🎉 Prize: {prize}',
value=f'🥳 **Winner**: {winner.mention}\n 🎫 **Number of Entrants**: {len(users)}',
inline=False)
winning_announcement.set_footer(text='Thanks for entering!')
await channel.send(embed=winning_announcement)```
How can I change the time to minutes, hours and days
!pip time-str
Use this mb
Ok
um, inappropriate channel
so i got ratelimited(using replit) and then used kill 1 in the shell and it still says im rate limited
oh well, but still "that" question wasnt related to dpy
the proxy url is the cached version of the url
don't use repl.it
kill 1 again, welp
ok
lmao
what does cached version mean lol
the url has been cached?
what do you expect the cached version
the cached is for storing data so it can be easily accessed without doing i.e api calls
ok thanks
Temporary memory
thats not what okimii said
nvm then
I mean Ik what cache is in a cpu
in some cases it can be temporary but it depends.
but i don't think thats the same
sure? because thats not what a cache is anyways
in this case bots use ram
It's just the information u store in RAM
It's stored in RAM cz the read write speeds of a RAM is more than that of a SSD or HDD
remember ram stands for random accessible memory
still used in different contexts
in this case you can say accessible
This debate can be taken to an ot channel too
hunter is the smartest among us all :)
i came here for the first time of the day to come to this
🗿
lmao, idk why i'm even talking about that
Wrong. Day started at 12 and u were here in the night too
totally not ot, we can talk about Hunter's greatness everywhere?
!ot anyways
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Yes pls!
i would love to
no😳
and i said the day not night
so you're wrong.
discord.errors.InteractionResponded: This interaction has already been responded to before how can i fix this and make it a continupus game?
you can either add a followup or edit the original message
oh
alr lemme try that
1 is the root process, I don't think that should change your IP
Depending on replit's architecture
it does change the ip
no but i did use edit_mesage?
Probably because it runs on docker or some other container
Killing root would probably kill the container and give you a new one
But new container could be in the same cluster as old one, same IP
?
replit runs on docker.....?
Probably do
Since you can just spin one up and shut it down after a user's done
Yea
thought so
Please add the Python formatting
why does the bot not give an answer when pressing the button ???!
what ?
!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.
Hey guys, I made a discord bot, but when I wait around 5 minutes and I train again to click on the verify button it says this
but the bot is still online
@maiden fable так ?
@bot.command()
async def text(ctx):
await ctx.send(
embed = discord.Embed(title= 'Команды сервера', colour=0xF1C40F),
components = [
Button(style = ButtonStyle.green, label= 'Like'),
Button(style = ButtonStyle.red, label= 'Dislike')
]
)
response = await bot.wait_for('button_click')
if response.channel == ctx.channel:
if response.component.label == 'Like':
await response.respond(context= "Молодец")
if response.component.label == 'Dislike':
await response.respond(context= "Дебил")
There is a default time for buttons
What do you mean with that?
Like there is a 1-3 minute time then they do not work anymore
yes
Only for some reason, when the button is pressed, the bot does not give an answer
how can I solve that?
Hmm
yeah buttons timeout after awhile, need to make a persistent button like so https://github.com/DisnakeDev/disnake/blob/master/examples/views/persistent.py
thanks!
@maiden fable and why was this format needed ??
@brave forge what is the issue
@maiden fable
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer
Can u print response.component.label?
wait_for for a button click.
gives nothing away
you asked me to withdraw it yourself
Wym
@maiden fable I must say right away I am not an Amerekan and I don't know English well so I don't understand your abbreviations
Ah, wym means What you mean
If anyone that knows or can shed input I'd appreciate it. Basically trying to get my command to work if member has assigned role or administrator permissions. I can only find documentation on, .has_any_role my commands currently work with , @commands.has_permissions(administrator=True) but I'd like to add in, @commands.has_any_role("SupportUS", "SupportCAD") as well as any user with admin permissions, or will I just have to use any role & put admin role in there?
@maiden fable
I did it on video and the dude on the vidos everything works, I wrote nothing works
@bot.command()
async def text(ctx):
await ctx.send(
embed = discord.Embed(title= 'Команды сервера', colour=0xF1C40F),
components = [
Button(style = ButtonStyle.green, label= 'Like'),
Button(style = ButtonStyle.red, label= 'Dislike')
]
)
response = await bot.wait_for('button_click')
if response.channel == ctx.channel:
print(response.component)
if response.component.label == 'Like':
await response.respond(context= "Молодец")
print(response.component)
if response.component.label == 'Dislike':
await response.respond(context= "Дебил")
print(response.component)
Change your code to this
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@sick birch do u mind helping @brave forge with his issue?
@maiden fable when the button is pressed, an error appears in the "Interaction Error" discord
^^^
And code?
^^^
I see
I don't remember button_click being a native discord.py event - are you using like discord_components or something?
He is using a 3rd party lib since components kwarg
how do you do this on discord.py
@sick birch yes, that's right, I do it using discord_components
The documentation is pretty bad. Check out this example I made: https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
Please let me know if that helps you, it would mean a lot to me ❤️
Ah, not much experience with discord_components. Not sure if I can help. Plus discord_components is frankly outdated, it's better to use the built-in buttons most of the forks have
I just don't know what else can be used to make the bot use the buttons
and I did that code on video and that dude has everything working. I have noticed more than once that there is garbage in Python that commands and event cannot work properly and do not create unnecessary problems. They are constantly spoiling something in discord bots and Telegram bots
But how can it work with specific Role & then users with admin perms as well for that one command, instead of one or the other. Can it check first & if no roles specified returned then it checks for admin permissions
@sick birch can you give me some advice ? is it better to do event and command in the same file or separate them ?? Using Cogs
Ah, you're following a youtube tutorial
Those are really bad and tell you to use code that doesn't work most of the time, and use bad design choices like using discord_components
Oh you want to use multiple roles?
Nvm, misread
for what ?
You want admin perms AND some role?
For using buttons?
Are you watching a youtube tutorial for that?
@slate swan you can stack has_permission and has_role
yes
@commands.has_role(...)
@commands.has_permission(...)
async def my_command(...):
...
I tried that, but once I add in administrator for permission, and the role specified doesn't have admin permissions it comes back
That explains it. I suggest you don't follow them since they're pretty terrible
I see 🤔
Let me try something else, one second
In that case, you could add a check inside the command, like so:
@bot.command()
async def my_command(...):
if not user_has_admin: return
if not user_has_role: return
just psuedocode of course
and then how to find out what how ?
Ok, that would probably work a lot better. Yeah I just tried restructuring it & it still came back, let me test out the above
What do you mean?
well, where can I study discord.py
The documentation and examples
is a VPS a good idea for hosting a discord bot?
Nextcord is best
Of course
I host like 20 bots on one and ye they fast
Dpy is better :)
which website do you recommend for a VPS?
Mmmmm no
Personally I use AWS
I also have a dashboard so i get a domain from R53
you cannot determine the best fork since all of them derive from discord.py and have their own cons
and then, personal opinions
How :OOO
when you type / into the message bar, discord shows all the commands from each discord bot.
how would I make it so my bot's commands also show up?
it's slash commands, and you have to sync them to make them appear
not normal commands
ik
my question is how?
How what?
What library are you using
await tree.sync() in on_ready()
No documentation found for the requested symbol.
ok
You have to load them into the server
no
Usually, yes, but in this case there's nothing wrong
nothing wrong with keeping it up to date
yeah but like you sync and it still will be up-to-date an hour later
bot.tree
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
does exist
should i not use client = discord.Client()
there's always many ways to do something in programming
you could do tree = app_commands.CommandTree(client) if using client
you can even make a tree instance and assign it to client
How can i create
Iwelcome message to send
Invite Tracker
like {member} joined invited by {user} {numInvites}
app_commands?
from discord import app_commands
ohk
?
discord.app_commands
yikes 'discord' has no attribute 'app_commands'
i think you need discord.py 2.0 for that
install d.py 2.0
I've changed to slash commands recently but im having a issue with the author function...
Error:
AttributeError: 'NoneType' object has no attribute 'author'
code?
@slash.slash() @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.User = None, *, reason=None): if member == None: reason = f"Please Mentionthe person you would like to ban {ctx.message.author.mention}" await ctx.send(reason) return await ctx.guild.ban(member, reason=reason) embed = discord.Embed(title=f"{member} Has been banned 🔨 ", description=f"✔ {member} Has been banned from {ctx.guild.name} by {ctx.message.author} for {reason}", color=(0x2fc8ec)) await ctx.send(embed=embed)
hm idk
Try ctx.author
Not ctx.message.author
Slash commands aren’t invoked from messages
what are persistent_modals ? how is it different from normal modals ?
!d disnake.ext.commands.Greedy
class disnake.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
it returns a list right?
please ping
Persistent modals work even when the bot restarts
theres no such thing as persistent modsls
but bot cant send modal at that time ?
there is
those are called persistent views
But what if it had already sent one before?

ohhh so that is why it is needed
How can i make welcome message to tag user who called new user on server
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
....
@commands.Cog.listener()
async def on_member_join(self, member):
channel = discord.utils.get(member.guild.text_channels, name='recording')
if channel:
embed = discord.Embed(description='Welcome to our guild!', color=random.choice(self.bot.color_list))
embed.set_thumbnail(url=member.avatar_url)
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.set_footer(text=member.guild, icon_url=member.guild.icon_url)
embed.timestamp = datetime.datetime.utcnow()
await channel.send(embed=embed)```
is this correct
Yeah it looks fine. But I would use embed.timestamp = discord.utils.utcnow() instead
nope, probaby an error with embed.timestamp
you should import datetime from datetime and then use utcnow
!e py import datetime print(datetime.datetime.now())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2022-04-16 18:46:52.515347
oh nvm it works

cool enuf, ill use something similar for welcome message configurations
😳 thanks for the idea kayle
lmao
np step bro
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Yes, shorter typing when using it also
import disnake
from disnake.ext import commands
from audio_bot import start, stop, finished_callback
with open('config.json') as f:
config = json.load(f)
token = config.get("token")
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("Bot is ready!")
@bot.commands()
async def record(ctx):
await start(ctx.author.voice.channel.id, ctx.guild.id)
@bot.commands()
async def stoprecord(ctx):
await stop(ctx.author.voice.channel.id)
bot.run(token)```
import os
import json
import discord
from discord.commands import ApplicationContext, Option
with open('config.json') as f:
config = json.load(f)
token = config.get("token")
bot = discord.Bot()
bot.connections = {}
async def start(channel_id: int, guild_id: int):
"""
Record your voice!
"""
channel = bot.get_channel(channel_id)
vc = await channel.connect()
bot.connections.update({guild_id: vc})
sink = discord.sinks.MP3Sink()
vc.start_recording(
sink,
finished_callback,
channel,
)
return("The recording has started!")
async def finished_callback(sink, channel: discord.TextChannel, *args):
recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
await sink.vc.disconnect()
files = [discord.File(audio.file, f"{user_id}.{sink.encoding}") for user_id, audio in sink.audio_data.items()]
await channel.send(f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files)
async def stop(channel_id: int, guild_id: int):
"""
Stop recording.
"""
if guild_id in bot.connections:
vc = bot.connections[guild_id]
vc.stop_recording()
del bot.connections[guild_id]
return
else:
return("There is no recording going on.")
bot.run(token)```
I know there are ton of issues but please tell
it totally works
when using pycord alone
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master · Pycord-Development/pycord
Wait fr
yeah
mee6 allows that, nextcord has a voice receive feature too,
Other than that discord.js library has that since djs v7 or smthing
anyone please?
how to make a server link in embed. That is, on whatever server the command is written, the name of the server is written there. I heard that you need to write like this '{message.guild.name }' but it doesn't work
i wanna make a list of items(like how json files work) that can be edited with commands, but idk any options other than json files
the ; 💀
@slash.slash() @commands.has_permissions(kick_members=True) async def kick(ctx, member: discord.User = None, *, reason=None): if member == None: reason = f"Please Mentionthe person you would like to kick {ctx.author.mention}" await ctx.send(reason) return await ctx.guild.kick(member, reason=reason) embed = discord.Embed(title=f"{member} Has been Kicked 🔨 ", description=f"✔ {member} Has been kicked from {ctx.guild.name} by {ctx.author} for {reason}", color=(0x2fc8ec)) await ctx.send(embed=embed)
How do i configure it so that members can't ban their self?
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.
whats the code to process commands
Ur passing in a list. You could use fetchone instead of fetchall
Also you should use this instead of the standard library sqlite3
!pypi aiosqlite
await it
It needs to be awaited
ok w8
same
import discord
from discord.ext import commands, tasks
import os
from config import DiscordConfig
class Bot(commands.Bot):
def __init__(self, command_prefix, **options):
super().__init__(command_prefix, **options)
self.on_ready_loop.start()
@tasks.loop(seconds=900)
async def on_ready_loop(self):
print('The BOT continues to work')
prefix = ['test']
client = commands.Bot(command_prefix=prefix, intents=discord.Intents.all(), strip_after_prefix=True,
status=discord.Status.dnd, activity=discord.Game('plz help'))
client.remove_command('help')
@client.command()
@commands.is_owner()
async def load(ctx, extension):
await client.load_extension(f"cogs.{extension}")
@client.command()
@commands.is_owner()
async def unload(ctx, extension):
await client.unload_extension(f"cogs.{extension}")
@client.command()
@commands.is_owner()
async def reload(ctx, extension):
await client.unload_extension(f"cogs.{extension}")
await client.load_extension(f"cogs.{extension}")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
client.run(DiscordConfig.bot_token)
code if so
You didn't await it in the last for loop ^^
We don't help with it here since this is illegal in certain countries.
This is because you can also record people that maybe don't give consent.
Use a pastebin next time
Use a pastebin next time
Ok
And who are you to say that may I ask you?
`@client.command()
async def invites(ctx):
embed = discord.Embed(
title="KrkanoidBot - Invites",
colour=discord.Colour.green()
)
total_invites = 0
for i in await ctx.guild.invites():
if i.inviter == ctx.author:
total_invites += i.uses
embed.add_field(name="Invites",
value=f"🔥 Pozvao si {total_invites} {'' if total_invites == 1 else 's'} membera na server!")
print(INFO + f'{ctx.message.author.name} je pozvao {total_invites} korisnika na server.')
embed.set_footer(text="KrkanoidBot - Made by Krkan#9999")
await ctx.send(embed=embed)`
I have one problem when user left server its dont delete one of totalInvites any who can help?
A human
Don't be mini mod
And why should I care about your personal preference
No reason
So I won't
Don't bother me for such a useless reason
He is just asking you 2 to make a pastebin since many people here find it annoying to flood the whole chat. If you don't like what the person is saying report it to @novel apex don't confront them.
hi guys i got my bot running finally with basic await ctx.send commands
but now i want to change it so that what ever comes after my command prefix is pasted into the url
so i got !ebay working but, i want it to work with !ebay television, so what would i write in order to get "television" stored into a variable
so i can format the ctx.send string
With commands, you can add arguments to the function in order to get arguments from the command
@bot.command()
async def ebay(ctx, search): # <-- Example argument "search"
...
ah ok sweet, thank you
how would i go about storing "search" so that i can format it into the url my bot sends out
If you enter !ebay television for example, the command is run, and the string "television" is passed in, and stored in search
i might be making no sense as im v new
ahhh
so on await ctx.send i could do a formatted string to include {search}
yep
thank you so much
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Hello - essentially I am trying to code a bot that sends a message when it detects a new game has been installed.
I have everything done, except for the sending a message part
For whatever reason when I do:
bot.run(token)
The script completely stops responding and does nothing,.
The script stops responding
bot.run isn't something that just runs and continues. It holds up the program in order to run the bot's event loop, and keep the program from exiting to allow it to keep running.
I would suggest trying to find a way to merge your code in a way the bot can run it, and now trying to have your code run the bot
await ctx.send(str.replace(' ', '+'(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")))
Find great deals on eBay for {search}. Shop with confidence.
would this work?
acc idk why i didnt just test it
!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.
await ctx.send(str.replace(' ', '+'(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=%7Bsearch%7D&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1%22)))
i got syntax error anyway so it deffo not working
Why do you have str.replace?
i need to swap out spaces with + signs
so if they do !ebay playstation 5, when it is formatted its playstation+5
otherwise url wont work
First thing, is that for multi-word arguments, you need to add a * argument
@bot.command()
async def ebay(ctx, *, search):
...
Second, you need to replace the character in the string in search, so you would call replace on that
try doing that on it's own before trying to mix it all together
oh yh thank you for that but im still getting the spaces in the url that is sent to server
What code do you have?
bot = commands.Bot(command_prefix='!')
@bot.command(name="ebay")
async def ebay(ctx, *, search):
await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")```
really appreciate this help
thank you
alright, now you just need to replace the spaces in search with +
You can do that right in those {} even
Well, do you know how to use replace?
!d str.replace
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.
Hmm
yes but not sure how to put it inside the url
you just put it in the {}
ah
You are doing the ebay thing no?
jo jon, yeah i am
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.command(name="ebay")
async def ebay(ctx, *, search):
await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")
Find great deals on eBay for {search}. Shop with confidence.
how tf i do upticks on mac
i been copy and pastin
I see an error or 2
oh yeah i think that was just copy and pasting error, i got it in pycharm
how to create the threads? like message.author.create_theads im lost tbh cuz idk how to create the thread for a specific message
ebay command is working an everythin i just need to get + instead of space
message objects themselves have a create_thread method
nah i get spaces in my url still with the code above
{str.replace(' ', '+')search}
have i done that in the wrong place
that is in the middle of my url
but it doesnt work, i tried message.create_thead but

thread*
my bad
yeah, actually, looks like you can use spaces @grave summit
you need to put a space in that ''
!d disnake.Message.create_thread
await create_thread(*, name, auto_archive_duration=None, slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a public thread from this message.
You must have [`create_public_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_public_threads "disnake.Permissions.create_public_threads") in order to create a public thread from a message.
The channel this message belongs in must be a [`TextChannel`](https://docs.disnake.dev/en/latest/api.html#disnake.TextChannel "disnake.TextChannel").
New in version 2.0.
oh yeah i have
nvm i think it should be message.channel.create_thread
i can use spaces in there but in the url it has + sign
check the url in that image
Well if you can use spaces why change it
its not clickable in discord
anyidea doe
https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=dunk low panda&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1
Find great deals on eBay for dunk. Shop with confidence.
Ah yeah, good point
i get that
would that be through an embed with a button in it
Just do an f string @slate swan
No I do not use an embed attached to it
Have you tried mentioning a user in an embed field? I remember that fields don't support all of the formatting that other things l;ike the description do
(f"Test test {author.mention}.")
it works the same doe
Yeah, embed field values aren't able to be formatted like other things on an embed, they only contain plain text
with/without embed
wym
Yea, it is cool actually.

await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")
so where could i put str.replace in that
where search is
im lost lmao idk what u r talking abt
i tried that and i get an error
I'm talking about Fiji's question
well what did you try, and what error?
How I made mine 😃
whats their question haha
about mentioning peope in embed fields, and how it was just showing plain text
{str.replace(' ', '+')search}
is there a way to see if someone has clicked a link type button?
replace is a method of a string object, which should be search
search.replace(...)
i see 
anyways
omg im stupid af
And it put the + for me
thank you, i thought the command was str.replace, but it meant the str which i want to replace haha

The small stuff really pisses me off
I don't think it sends an interaction or anything, it's just a link, so no
its working, thank you @frozen patio @wicked atlas wish i could thank you
actually so happy with that, im falling in love with coding icl
Welcome 😄
Yea it is very nice
I tried to use an ipc using python but umm it failed
Inter Process Communication
Connecting a bot to a webserver dashboard
honestly dashboard is eh pain 
i should try
Ima reopen the folder and fix it
ohhh you're the one who were stuck in the manage_guild permission?
Yes, but I think I can fix this not sure hmm
lmao
just dont give up cuz ye
Erm, keep it server appropriate please.
I edited it but I will
I did but I feel like it needs to be completed
just keep googling
or read the docs
It is quart-discord I think
btw how Can i create the threads i mean should i fetch the message or 💀 wut
ye
!d discord.Message.create_thread
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a public thread from this message.
You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.
The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel").
New in version 2.0.
You can only fetch messages yes, message don't get cached.
i just want to create the thread so i think that will work fine
You can also create a thread using a partial message, if you got the message id instead of the object.
partial message?
whats that 🤔
!d discord.PartialMessage
class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.
There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following...
alr 
Like this 💀
They do, but for whatever reason discord.py decided not to expose that
I have no idea what this is
Hmm yeah some apparently
!d discord.DMChannel.get_partial_message
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Changed in version 2.0: `message_id` parameter is now positional-only.
discord/state.py lines 461 to 462
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None```
Have you coded this yourself?
I did
But there is no send_json in my code 💀
send_json is called internally from your IPC library
Yeah, so do I need to make a json file
IPC works by opening up a websocket connection and sending information through there, that's how they achieve inter process communication
Are you using a nextcord extension? Since the ipc is a discord.py lib.
No, the problem is somehow somewhere, your websocket is a NoneType
Which I'm assuming is just the sentinel value here or something?
Make sure you read whatever documentation you followed properly, and make you open a connection
I used nextcord-ext-ipc
The main IPC lib also stopped as year ago.
Mmmmm
Do you got git? Since most people just CTRL+SHIFT+H the entire old project.
Well I cannot find the error in my code 👀
No 👀
!pypi nextcord-ext-ipc
Did it ever work?
No
Could you show how you connect?
Have you tried running the examples if it even still works?
I have these
why is "embeded_response.image.width" returning "Empty"?
the image is showing normal if i send the embed
embeded_response.set_image(url = em_image_url[1])
embeded_image_resolution = f'{embeded_response.image.width}x{embeded_response.image.height}'
I never started my IPC server 😐
!d discord.Attachment.width
The attachment’s width, in pixels. Only applicable to images and videos.
Type: Optional[int]
"Possible attributes you can access are:" from doks
does it mean i can change the pixels?
I mean you can change the number but that wouldn't change the image.
but its a return value how can i change it?
it works if i try to return the url of the image, width and heigth doesnt
dont you think it means that you would get the width and heigth of the image?
because i dont input anything, i get a value returned
the url for example
!pypi fortnite
:0 Dead chat
Anyone here whos used digitalocean, how would i upload my code to a droplet i have running?
Does anyone know when heroku will allow github connection again?
!d discord.Interaction.user
The user or member that sent the interaction.
Is there a way to check if a use (that use a command) has a role using the ID of this role?
Like I have the ID of the role stored in a variable and I want it to check if this user has this role
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
check these
Thank you ❤️
btw is there a way to get the the author who sent the message that has the thread? like the channel.owner_id returns the user who creates the thread but i want the one that sent the msg
idk how to explain 
uhm im using buttons py @disnake.ui.button(label = "Offline", custom_id = "offline", style = disnake.ButtonStyle.grey) async def offline(self, button: disnake.ui.button, inter: disnake.MessageInteraction):
then use a wait_for
!d disnake.MessageInteraction.message
The message that sent this interaction.
Actually, not sure if that would work
alr 
inter.message.author returns the bot 
Yea, I was thinking about that
does anyone know where i can find good instructions for a twitter bot, i want a bot for channel that posts those messages to twitter
nothing against TOS
just posts the image and text from a message through a tweet
That’s not within the scope of this channel unfortunately
ok no problem , thank you anyway
even if its a discord bot that does it?
aren't twitter bots against tos?
i couldnt find anything but if im wrong thats fine ill just stop
also, wdym by instructions
just like a guide for it, im not sure what packages may need to be installed
i dont think there is any TOS against twitter bots unless its for smth called "mail bombing" and other bad stuff like viruses
Twitter allows bots, but they have a few guidelines
is there a way to do it using something similar to that?
if ctx.message.author.guild_permissions.administrator:
i just want success posts to be shared on twitter when posted in success channels on discord so from what i have read thats fine with TOS but not sure what package is used and cant seem to find one
ye
!d discord.ext.commands.has_guild_permissions
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").
New in version 1.3.
what is a "success post"?
Yeah I know about that, I'm trying to have it so it is:
if ctx.message.author.guild_permissions.administrator or #user has a role (using ID):
The ID is stored in a variable
just make a POST request to https://api.twitter.com/2/tweets with the required headers to post a tweet
role = ctx.guild.get_role(id)
if ctx.message.author.guild_permissions.administrator or role in ctx.author.roles:
``` idk tbh
basically when me or my friends get a pair of shoes from drops etc we post success posts in a success channel
I seeee
well I will try thx a lot 
anytime 
O
quick question to save me 5 mins testing this, can you @ someone in a modal
Wdym model?
i think he's talking abt discord.ui.Modal?
Ikr
Trying to find a way to check if role is a @role ping, and get the ID of it
async def setmanager(ctx, role):
I am gonna learn how to make a leveling system
Typehint it to discord.Role
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
👀
I saw that
You still need help or no?
With an event
an on_raw_reaction_add event
I cannot spoonfeed you
Mine is very complicated, but it is for a ticket system
But you could do this, ig
You need to make where the user clicks on the reaction, it will send a DM
i wouldnt
Why?
the documentation is horrible
Show me
Get off replit
It's also where you will be ratelimited
Did you pass in message?
It's not
Payload doesnt have message
repl trash 🤣
agreed
VS Code is surpreme
!d discord.RawReactionActionEvent.message_id
The message ID that got or lost a reaction.
for a code editor at least
Those two arent really related but ok
Since hes actually using it for hosting
Mk
.
Well you have to work on it yourself, try printing out the variables
What did you print?
bruh
discord.Message.id you didn't specify it
look, i used to code in dpy and probably don't know much now but i guess it should be payload.message.id
try it
.
Where and who
You need an instance of the discord.Message class
He also defended replit
Capitalization matters
No you did Message
We can see in the error you did Message
Isn't it message_id
oo
I don't work alot with events
yeah it's message_id prolly
But i'm checking the docs
docs are pretty easy to use and their helpful!
"helpful" is debatable
doubt
Documentation is only helpful when the person who wrote them isn't incompetent
i think you ment read them?
No, sometimes people just write horrible documentation
For an example, when I have to write documentation I just want them done as quickly as possible cause I'm lazy
in this case its not really bad written. it would be helpful if you actually had the skill to even use the library and read its own documentation
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
someone explain to me why it doesnt work now? I did nothing on the code i just restarted my bot. It worked before!
I found out how to fix it but its because of a on_message event, any ideas why?
With how commands work, they rely on the default behaviour of on_message, which calls Bot.process_commands(message), so to fix this issue; you'd change @bot.event to @bot.listen() or manually add await Bot.proces_commands(message) to your on_message
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
What's wrong?
class ApplicationModal(ui.Modal):
def __init__(self):
x = ui.TextInput(label='Test')
self.add_item(x)
async def on_submit(self, interaction):
await interaction.response.send_message('Test success!', ephemeral=True)
Ignoring exception in view <RulesView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Accept' emoji=None row=None>: Traceback (most recent call last): File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ui/view.py", line 413, in _scheduled_task await item.callback(interaction) File "/data/data/com.termux/files/home/codes/otaku/extensions/applications/apply.py", line 26, in accept await interaction.response.send_modal(ApplicationModal()) File "/data/data/com.termux/files/home/codes/otaku/extensions/applications/apply.py", line 16, in __init__ self.add_item(x) File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ui/view.py", line 307, in add_item if len(self._children) > 25: AttributeError: 'ApplicationModal' object has no attribute '_children'
if i run pip install -e path/to/package to install a local package, and change something in the code, when would the change take effect when that package is used in my bot's code? do i have to restart the bot for it to reflect the changes in that local package?
I see i see, thanks!
Also i answered this question in the discord.py server so take a look there 
or reloading the cogs if you use them would work too
Oh awesome, that's much more convenient
given that the libraries should be imported in that cog itself
Gotcha
Hey did you mean that the import statement needs to be in the cog class or the cog file? Because having it in the cog file (at the top) doesn't work with reloading the cog
It doesn't, but it doesn't reflect any changes by just reloading (bot.reload_extension) the cog
Oops meant to reply to the 2nd message
and the other one?
Alright that's still pretty neat so I'm not complaining. I've been having to pip install --upgrade ./gists.py every time before i learned about pip install -e ./gists.py so this is a huge step-up
Thanks!
https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
Does anyone know where the message goes after submitting?
You have first statement in your function double indented
Maybe you forgot if isinstance(error, MissingRequiredPermissions)?
can you give me fixed code ?
@bot.command()
async def kick_error(error, ctx):
await bot.send_message(ctx.message.channel, "You do not have permissions")
elif isinstance(error, BadArgument):
await bot.send_message(ctx.message.channel, "Could not identify target")
else:
raise error
@vale wing
raise OperationFailure(errmsg, code, response, max_wire_version)
pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
if you wanna make seperate error handlers for seperate commands, this is the syntax to follow:
@bot.command()
async def kick(ctx):
...
@kick.error
async def kick_error(ctx, error):
...
where ctx is the Context (like a normal command) and error is the error which occurred
db = cluster["UserData"]
collection = db["UserData"]
wordstotestby = [
"word1",
"word2"
]
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='MongoDB'))
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name}: {ctx.content}")
myquery = { "_id": ctx.author.id }
if (collection.count_documents(myquery) == 0):
if any(x in ctx.content for x in wordstotestby):
post = {"_id": ctx.author.id, "score": 1}
collection.insert_one(post)
print(f"Word detected")
else:
if any(x in ctx.content for x in wordstotestby):
query = {"_id": ctx.author.id}
user = collection.find(query)
for result in user:
score = result["score"]
score = score + 1
collection.update_one({"_id":ctx.author.id}, {"$set":{"score":score}})
print(f"Word detected")```
bro why is this error coming?
did you put in the valid creds in your atlas url?
i think i have put wrong pass
but where do i reset it i dont know
you forgot the passcode....?
yeah
i terminated it
@slate swan
@commands.has_permissions(kick_members=True)
@bot.command()
async def kick(ctx, error, user: discord.Member, *, reason="No reason provided"):
await user.kick(reason=reason)
kick = discord.Embed(title=f":boot: Successfully Kicked", description=f"User: {user.name}\nReason: {reason}\nCommander: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=kick)
await user.send(embed=kick)
yes?
So maybe that's right?
I added an error!
"added an error"
are you okay?
early:
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
now:
async def kick(ctx, error, user: discord.Member, *, reason="No reason provided"):
nnnnoooooooo
wait what
thats so wrong
@barren sand
that maybe working as string?
yeah itll work as a parameter
refer to the reply to the message i pinged you with
Have you used functions in python before?
@barren sand
no
such an honest human
I need help
And not your stupid cynics
if you want help me or do not give me an answer
I just gave you the answer but you're simply ignoring that...
As you know I do not know python programming
yeah ur pinged
Can you write me the correct code?
idk that udk ;-;
A person familiar with normal python programming knowledge would not allow this error
@bot.command()
async def kick(ctx, user: discord.Member, reason="No reason provided"):
...
@kick.error
async def kick_error(ctx, error):
...```
thank
hi Black
db = cluster["user"]
collection = db["data"]
is it wrong?
bot.event ?
@kick.error
This is so painful
To watch
Wish you the best ashley
ill just go away from here

it is not necessary () ?
no
i'll just go enjoy easter 😔
yeah.....
Do the English have such a love for guests?
no errors?
see the logs
sorry?
10 minutes earlier, you just asked me to die
and no, I wont help you anymore, first learn how to behave properly with others
Logic 0,0
For you I am nothing
And why should my word mean anything to you?
If I told you to fly, would you fly?
What do you think ? Do you think I liked it?
Hey I am making a bot with giveaways and I was wondering how I could convert 1m to 60s and 1d to the amount of seconds?
ask depressed @slate swan
she know python 60%
Can you send me a friend in 2 minutes? I have to tell you something and then unfriend me
@slate swan
db = cluster["user"]
collection = db["data"]
author_id = ctx.author.id
guild_id = ctx.guild.id
ping_cm = {"command":1}
ping_cmn = {"_id":author_id}
collection.find(ping_cmn)
collection.update({"_id":author_id},{"$set":{"Level":1}})
await ctx.send("Registered")```
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Collection' object is not callable. If you meant to call the 'update' method on a 'Collection' object it is failing because no such method exists.```
@slate swanbro
!tempban 925079016174682213 1w that is absolutely unacceptable behaviour. read our rules and code of conduct if you return
:incoming_envelope: :ok_hand: applied ban to @obtuse obsidian until <t:1650793220:f> (6 days and 23 hours).
:ok_hand: pardoned infraction ban for @obtuse obsidian.
!tempban 942840399767154711 1w that is absolutely unacceptable behaviour. read our rules and code of conduct if you return
:incoming_envelope: :ok_hand: applied ban to @barren sand until <t:1650793282:f> (6 days and 23 hours).
YEAH IS UNACCEPTABLE
Self hosting 
Bruh really that guy blamed us cuz he doesn t know python lol
can I annoy you even though I know you did that by mistake
Hey! I am using a function called CheckManagerPerm() in a cog in this way:
def CheckManagerPerm(ctx):
manager_role = ctx.guild.get_role(int(managerID))
if ctx.message.author.guild_permissions.administrator or manager_role in ctx.author.roles:
return True
else:
return False
#checkperm
@commands.command(help="Check if you have the permission to use the bot.")
@commands.guild_only()
async def checkperm(self, ctx):
if CheckManagerPerm(ctx) == True:
#more stuff
for some reason its sating that:
Command raised an exception: NameError: name 'CheckManagerPerm' is not defined
Is there a specific way to def functions in a cog?
To get an attribute in a class use self.<attribute>, so in your case to call the function, do self.CheckManagerPerm(...).
welcome back
Oh I see
let me try !
It seems to run, but now its raising another error when I just run .checkperm
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: CheckManagerPerm() takes 1 positional argument but 2 were given
Oh, to define a function within a class should have self as its first parameter (only if it's an instance method): def CheckManagerPerm(self, ctx):.
I see
and do I have to have it as if CheckManagerPerm(self, ctx) == True: in the command?
No, you don't need to pass the self argument manually, it is passed automatically by default.
Do you have discord.py on master branch version? You can see this by printing discord.__version__ or by doing pip show discord.py on the terminal.
You're most welcome!
does it actually not run or is vscode just not resolving correctly?
try running it then
thanks a lot
im importing the discord library and says this message: "
anyone tells me why?
If you try to run it, does it print anything to the console?
ok try py -3.10 -m pip install git+https://github.com/Rapptz/discord.py just to make sure that dpy is being installed on the same python version you're using
that's the only reason VSC wouldn't be resolving it if it's installed
token is currently a NoneType (the None keyword), you need to pass a string of your token.
You can use the -U flag to check if there's a newer version, so do this: py -3.10 -m pip install -U git+https://github.com/Rapptz/discord.py.
Hello, I have a bot that has a ticket tool (server enquiries, questions, mod applications, etc), I have created the ticket channel but I have an issue, how am I able to make it so that admins and the ticket creator can see the channel, but the rest of the server not able to see it? I am using py await ticket_channel.set_permissions currently.
Question, I am in a cog and I am using a variable called managerID this is how its defined:
managerID = open("managerID.txt", "r").read()
I use it in a method like that:
def CheckManagerPerm(self, ctx):
manager_role = ctx.guild.get_role(int(managerID))
if ctx.message.author.guild_permissions.administrator or manager_role in ctx.author.roles:
return True
else:
return False
For a reason it keep on saying NameError: name 'managerID' is not defined and I don't get why is there an other way of defining a variable in there?
how do I fix it
?
Admins by default would be able to see every channel, but for the creator you can set the permission like this (assuming you've set view_channel permission to False when creating the channel):
await ticket_channel.set_permissions(author, view_channel=True, send_messages=True, read_messages=True)
I'll try now, thank you!
I can't figure out the invalid syntax
I have an issue,
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: target parameter must be either Member or Role```
embed = discord.Embed(title="Admin Commands", color=0xC98FFC)
embed.add_field(name="bubble!purge (AMOUNT)", value="Purge a number of messages in a channel", inline=False)
embed.add_field(name="bubble!geolocate (IP)", value="Gives general geolocation information about an IP", inline=False)```
i cant figure out the invalid syntax
Where do you define managerID? If it's a class variable, E.g.
class MyClass:
my_var = 1
``` you can use `self.my_var` to get the variable, but if you do it in another place and it's dynamic (may change), you can use a botvar (see `!tag botvar` for more information).
Show the code above the elif statement
Try wrap it in ( )
Probably not the problem
elif (arg.lower() == "admin"):```
Ya never know.
I do
embed = discord.Embed(title="Webhook Commands", color=0xC98FFC)
embed.add_field(name="bubble!decode (BASE64 CODE)", value="Decode", inline=False)
embed.add_field(name="bubble!curl (WEBHOOK)", value="Find information about a webhook", inline=False)
embed.add_field(name="bubble!nuke (WEBHOOK)", value="Delete a webhook", inline=False)
embed.add_field(name="bubble!troll (WEBHOOK) (MESSAGE)", value="Sends any message of your choice to a webhook", inline=False)
embed.add_field(name="bubble!spam (WEBHOOK) (MESSAGE)", value="Spams a troll message to a webhook", inline=False)
await ctx.send(embed=embed)
elif arg.lower() == "admin": (INVALID ONE)
embed = discord.Embed(title="Admin Commands", color=0xC98FFC)
embed.add_field(name="bubble!purge (AMOUNT)", value="Purge a number of messages in a channel", inline=False)
embed.add_field(name="bubble!geolocate (IP)", value="Gives general geolocation information about an IP", inline=False)```
It would be helpful if you send the whole code, but generally you need to do E.g.
token = "the_token"
bot.run(token)
On it, thank you
!tag botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
@visual island
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print("I'm in")
print(client.user)
@client.event
async def on_message(message):
if message.author != client.user:
await message.channel.send(message.content[::-1])
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)```
Where's the red squiggly lines?
To use this botvar do I have to call it using bot.name? Or just to define it?
next to where i typed (invalid one)
Ohh.
Does it actually error invalid syntax
Also show your entire code
Show your entire code
.
A possible reason is that you have a folder/file named discord.py or discord, but you could check by doing print(dir(discord)) for seeing the possible attributes for discord.
await ticket_channel.set_permissions(author, view_channel = True, send_messages = True, read_messages = True)```
Here's the line that gives the issue.
Wait, I think the value of author is message.author.id.
Yes, I just realised that just now.
It seems that you don't have anything named DISCORD_BOT_SECRET on your environment variables.
Yep, sure worked!
It can be anything, it's the same as defining normal variable, but this is setting an attribute to your bot object.
I see
And how do you use it cogs?
cause it will say that bot is not defined im pretty sure
After you did import discord.
self.bot is your bot object in cogs or if you define it differently it would be the variable which holds the second parameter (after self) on the cog's constructor.
I see
Thanks a lot again 
No, it would be
import discord
print(dir(discord))
``` and make sure you run it and show what it prints.
I guess they did run it before, at least someone told them to.
The await ctx.send was making it invalid
On the sidebar of replit, find the "lock" image, click it and add the environment variable there.
with the name of DISCORD_BOT_SECRET?
You need to pass the intents keyword to the commands.Bot(), so it's something like bot = commands.Bot(command_prefix=..., intents=...). Change the ... to the value you want to pass.
Yes, sure, and make sure you have your bot's token set to the value.
what is the difference between Discord.Client() and Discord.ext.bommands.Bot()?
Traceback (most recent call last):
File "main.py", line 17, in <module>
client.run(token)```
shows this error
In your case, it should be something like this:
bot = commands.Bot(command_prefix="n!", intents=discord.Intents.default())
``` or you can pass `discord.Intents.all()` too.
!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.
anyone?```




whats ipc


