#discord-bots
1 messages · Page 855 of 1
I mean, it will return a number between 0 and 1
Wait nvm
U will have to, uhhhh, use random.choice ig?
with weights
mhm
but how would i make the probability of picking the win statement to 1%
import random
print(random.choices(["win", "lose"], weights=[1, 99]))
thankyou ❤️
how to check if the bot is ratelimited
Turn on logging
ok
If I turn on intends, do I have to kick out the bot and re-invite it?
no
I did but eh, I guess Ive messed something up
!intents make sure you have both
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 the Members and Presences intents, which are needed for events such as on_member 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.
in your code, and enabled in dev portal
Yeah I did that
@client.command()
async def raffle(ctx):
win = discord.Embed(
description='You Won!',
)
lose = discord.Embed(
description='You lose!',
)
member = ctx.message.author
role = get(member.guild.roles, name="Giveaway")
random.choices([win, lose], weights=[1, 99])
if lose:
await ctx.send(embed=lose)
elif win:
await ctx.send(embed=win)
await member.add_roles(role)
await ctx.send(f"{member.mention} has been assigned the role: {role.name}")```
Can someone tell me what's wrong with if statement it keep sendin you won
Sorry if i did any dumb thing, I'm new to this
Hmm, change the weights to 99, 1
that's it??
Ig?
i thought something is wrong with if statement
Qqi
if lose:
Wait*
is that fine?
idk why is this happening 😥
i had made a bot with discord.py
today i added giveaway commands in it
but they dont work
but... when i comment out the other commands ( all of them leaving the giveaway one ) it works totally fine
U need to assign the randoms.choice to a variable
And need to see if that variable is lose or win
import discord
import os
client = discord.Client()
Picture = ["https://discord.com/channels/@me/946254767565439036/946310674101989397", "https://discord.com/channels/@me/946254767565439036/946310844155826186"
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.hug'):
await message.channel.send((random choice)Picture)
client.run(os.getenv('TOKEN'))
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
if lol == win:
. . .
elif lol == lose
. . .
if lol == win:
do this
what is the problem of this code
yea got it thank u so much ❤️
any err?
The message.channel.send function
random.choice(Picture)
oh
but the error also said
File "main.py", line 10
async def on_ready():
^
SyntaxError: invalid syntax
okay
idk why is this happening 😥
i had made a bot with discord.py
today i added giveaway commands in it
but they dont work
but... when i comment out the other commands ( all of them leaving the giveaway one ) it works totally fine
HELP ME PLEASE
Can't help without any code buv
code
error?
client.run(os.getenv('TOKEN'))
no error
it said File "main.py", line 21
client.run(os.getenv('TOKEN'))
^
SyntaxError: invalid syntax
client.run(os.getenv('TOKEN'))
oh
so we need code with command, that doesn't work
still the same error?
you need full code?
Isn't that's what he's doing?
lol
!paste can be used
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
yes
yeh ik but thats workign for me
Show latest code
import discord
import os
client = discord.Client()
Picture = ["https://discord.com/channels/@me/946254767565439036/946310674101989397", "https://discord.com/channels/@me/946254767565439036/946310844155826186"]
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.hug'):
await message.channel.send(random.choice(Picture)
client.run(os.getenv('TOKEN'))
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
error is File "main.py", line 21
client.run(os.getenv('TOKEN'))
^
SyntaxError: invalid syntax
Yea
@client.command()
async def raffle(ctx):
win = discord.Embed(
description='You Won!',
)
lose = discord.Embed(
description='You lose!',
)
lol = random.choices([win, lose], weights=[1, 99])
member = ctx.message.author
role = get(member.guild.roles, name="Giveaway")
if lol == win:
await ctx.send(embed=win)
await member.add_roles(role)
await ctx.send(f"{member.mention} has been assigned the role: {role.name}")
elif lol == lose:
await ctx.send(embed=lose)```
Now the bot isn't even responding, no error either
ohh
Try printing lol
lol is not embed, win and lose are embed
where?
Sorry i didn't get it
Anywhere
It's just choosing any one of those embeds tho
so he need not ["win", "lose"]
[win, lose]
Oh wait... Missed that, sorry
I tried that too it's not working either
choices return list
if lol == [win]:
i think
Ah yes
okok let me try
!discord
Use choice, not choices
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
choice has weights?
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
Nope it doesn't
My bot is online but it said this
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Test/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_message
await message.channel.send(random.choice(Picture))
NameError: name 'random' is not defined
import random
and it can not send message back
Yup
in file
oh ok
xd
@buoyant quail https://paste.pythondiscord.com/wumijebuko
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Test/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_message
await message.channel.send(random.choice(Picture))
NameError: name 'random' is not defined
help me this error
which command don't work?
Giveaway
ok
That worked bro thank you so much ❤️
Why i have this error?
command code:
@bot.command()
async def say(message, *,args):
await message.reply(args)
message.reply() ...
Thats works fine but idk i changed and the bot sends this error lol
Traceback (most recent call last):
File "/home/runner/Test/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_message
await message.channel.send(random.choice(Picture))
NameError: name 'random' is not defined
help me pls
NameError: name 'random' is not defined
import random
where?
Obviously it will
You must import the modules before using
any can help me?
pd: message.reply() works fine but idk why i get this error
❤️
bot response totally nothing?
by me it workes
It replies to $ping but not $giveaway
the first argument in commands is always a Context object
And your error means that you use the say command without providing any arguments
and so on. i just copied ur command
when i put the arguments the bot give that error lol
You pasted the whole code?
no
well, good night
K GN
What error
Add client.process_commands(message) in your on_message event
Or just change .event to .listen()
Where
Ok lemme try
But
but?...
That's .command()
No , on_message is an event
Commands and events are different thing
i am benginer in Python
i create bots in node js, you know how i can create an:
if(!variable) return;
in py?
if not variable: return
if not variable : return
oh god thanks❤❤
you can add the ; too if you want it to be fancy lol
and brackets
cause message is ctx
Client.Event to client.Listen()?
try message.message.reply
is it possible to make a python code like user sends a image of dog , and i want to identify and compare it with the images i have of dog breeds
yes but its not related to this channel
ctx where
uhh the user is a discord user
i not use ctx before and works
which user
yes it will
now idk what i change and the bot give that error lol 😂😂
like for eg u send a image , my bot inputs it and tells breed of dog
not works
machine learning
and you want breed so deep learning
😂😂
Well to be more precise it was pokemon related too lol
its a self bot?
self. ?
its dpy code
Bot normal
well i think message is replaced by ctx
command.Context can be any
mhmm maybe not expert
but this snippet works
async def print(ctx, arg):
await ctx.channel.send(arg)```
it worked thanks!!!!
You may use some api to get the images of the dog breeds
Or do you want to compare it with local ones?
hey guys!
how do i make py (6, user_balance) the minimum 6 dollars and max 40% of user_balance?
what?
bad way to explain it but basically
So right now I got it where you can steal between 6 dollars and their entire balance, but I want to make it where they can only steal up to 40% of user balance
random.randint(6, int(user_balance * 0.4))
thank you math isnt my strong suite
{:.2f}
``` how can I make this minutes with seconds, instead of just seconds?
To use mobile presence on your bot, just add this code to the main.py file of your bot and it will work:
async def mobile(self):
import sys
payload = {'op': self.IDENTIFY,'d': {'token': self.token,'properties': {'$os': sys.platform,'$browser': 'Discord iOS','$device': 'discord.py','$referrer': '','$referring_domain': ''},'compress': True,'large_threshold': 250,'v': 3}}
if self.shard_id is not None and self.shard_count is not None:
payload['d']['shard'] = [self.shard_id, self.shard_count]
state = self._connection
if state._activity is not None or state._status is not None:
payload["d"]["presence"] = {"status": state._status, "game": state._activity, "since": 0, "afk": False}
if state._intents is not None:
payload["d"]["intents"] = state._intents.value
await self.call_hooks("before_identify", self.shard_id, initial=self._initial_identify)
await self.send_as_json(payload)
discord.gateway.DiscordWebSocket.identify = mobile
(Courtesy of discord.py server)
(Just saying)
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Eevee, are you still lurking here? 👀

Do u seriously have a self bot on?!
Lmao
Which tells u everytime your name is said in a message smh
Why would I self bot anyways, its not legit
To see whenever someone thinks/talks about u 👀
lol
Hey hey, no
Nor am I so free to do so
Lmao who knows. I mean u do lurk here everytime someone's talking about you. Coincidence? Idts
This one was a coincidence, I just came back from an exam lmao
Hmmmmm cool
!ot anyways
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
I'll take my leave now
Nah am done, wont be back for another two months or so
Bet
Bet
someone's having their last goodbyes
No thanks
huh?
Lmao
am sleepy
go to sleep because ||Joe Likes Forza :)||
I hate it anyways ot
command ideas just for you
yeps
I have a lot of ewwy commands ngl
okay not many
thanks didnt think of those..
xD
70 commands dont come from here and there
U know... search for this bot named owo. It literally got every. shitty. command. you. can. think. of.
pat, kiss, snuggle, cuddle, handholding :) and stuffs
I'll ask okimii to add it to the Akeno server
They come in the category of shitty commands for me, thanks
those arent shitty-
Meh
i should be sleeping instead of coding oh well
I think of that at 2 in the morning
2 morning?
2 in the morning -> 2 AM
it's night :
btw
Heh?
can slash command names have spaces in between?
Nope
i think no
uhhh
Subcommands*
File "main.py", line 82
message = await ctx.send(embed=embed)
^
IndentationError: unexpected unindent
def didnt take 3/4 hours 
help
this full code
U r most probably indented with an extra space in that line
so if message already exists, will it come?
?
there is no space
NOOOOOOO WHY U DO THIS TO MEH
lol
plshelp
had to be done 
pls
send sc im confused
learn python first ..
ik but
uh
From line 27
oh jeez
if you know python you can't get indent error
Your indentation lol
this my arch nemesis
thats the indentation?
newbies make mistakes
?
how do u not understand
like remove ALL THe SPACES?
2 tabs in lines 27-33
tab is indenting
i use replit
or use vscode if u want the text editor feel
oh god
XD
i tabed line 82 and this is what i get
File "main.py", line 80
message = await ctx.send(embed=embed)
^
IndentationError: unindent does not match any outer indentation level
use visual code it helps with errors and shows if their needs to be an indent
pycharm is best
ok but ill have to install
havent tried it
anyways
pls help
anyone?
my new problem
File "main.py", line 80
message = await ctx.send(embed=embed)
^
IndentationError: unindent does not match any outer indentation level
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
where?
the third button from the top left
lol
of course bruh
ok
just text?
in minecraft?
yes ig
highlight lines 46-50, then press tab twice. first remove the spaces from
message = await ctx.send(embed=embed)
there is no button in top left
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
so i have to go to replit highlight lines 47 to 50 and click tab, right?
@cosmic agate you should check out the docs and youtube some stuff about python so you learn basics like indenting and where to find things on your keyboard!
highlight message = await ctx.send(embed=embed and drag it down and press tab
File "main.py", line 80
message = await ctx.send(embed=embed)
^
IndentationError: unindent does not match any outer indentation level
lol bruh
oh god...
ok
i wonder why
did you make this code?
clearly not
nah stackoverflow with some minor modification
31 line need indentation too
i thought you were done with me
that is correct
im going to bed fuck this
!indents
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
what's that new timestamp thingy? R> something
?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
here I guess?
ah yeah that one, thanks
!d discord.utils.format_dt is also there
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
okai
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Jk
Bro
How to make commands locked to certain user ids
!d discord.ext.commands.check
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
That’s for owner tho?
Is it just for permissions I thought
It can be used to make custom checks
What if user ids are on txt file
u gotta use open
does
how/can I have groups for slash commands (using nextcord)
Yes, look into subcommands
any docs or such?
Idrk sorry
I tried commands.group like a regular command, it no work :(
splendid, thanks
basically ```py
@slash_command(....)
async def cmd(...
...
@cmd.subcommand(...)
async def subcmd(..
...```
cool
how to make this
?
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
await interaction.response.send_message(..., ephemeral=True)
I have a command with a while loop waiting for an input to a dropdown menu. It works exactly as expected, but it keeps responding on that message even after several hours have passed. I want to allow it to timeout if a certain amount of time has passed, but it only does anything in the loop if the message is interacted with. How would I fix this?
while True:
inter = await message.wait_for_dropdown()
if inter.author.id==ctx.author.id:
label = inter.select_menu.selected_options[0].label
for idx,_ in enumerate(_pageData):
if _pageData[idx]['DIRECTORY'] == label:
_newDir,index = _pageData[idx]['DIRECTORY'],idx
embed = discord.Embed(title=_pageData[index]['TITLE'])
embed.set_footer(text=directory)
if 'IMAGE' in _pageData[index]:
embed.set_thumbnail(url=_pageData[index]['IMAGE'])
for i in _pageData[index]['SECTIONS']:
print(i)
embed.add_field(name=i['NAME'], value=i['TEXT'].replace('<COMMA>',','), inline=i['INLINE'])
await message.edit(embed=embed,components=[SelectMenu(placeholder=_newDir,options=listOptions)])
pyTraceback (most recent call last): File "C:\Users\user\Desktop\Blossom Bot\main.py", line 2, in <module> from discord.ext import commands File "C:\Python37-32\lib\site-packages\discord\ext\commands\__init__.py", line 13, in <module> from .bot import Bot, AutoShardedBot, when_mentioned, when_mentioned_or File "C:\Python37-32\lib\site-packages\discord\ext\commands\bot.py", line 37, in <module> from .core import GroupMixin File "C:\Python37-32\lib\site-packages\discord\ext\commands\core.py", line 1127 for alias in command.aliases: ^ IndentationError: unexpected indent [Finished in 1.9s with exit code 1] [shell_cmd: python -u "C:\Users\user\Desktop\Blossom Bot\main.py"] [dir: C:\Users\user\Desktop\Blossom Bot] [path: C:\Python37-32\Scripts\;C:\Python37-32\;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\GtkSharp\2.12\bin;C:\Program Files\Microsoft VS Code\bin;]
why isent it working?
the line for alias in command.aliases: is indented incorrectly
what should i do to solveit?
make it so that that line is aligned on the left with the line above it
where do i use bot.wait_until_ready?
@autumn trench
uhh, for starters you should probably change your token
📸
it's really easy to undo iphone scribbles
nah jk
where you want to coroutine to block till the bot is ready
ummmm askusaly thats ms pain scriibles
still 
ohh that looks like a problem with the package itself actually now
i would recommend you try reinstalling discord.py
i want to make it so if sombody says !record it would copy that person next message and send it back. is that possible?
add person to list add in on_message check if person in list: send
but how would i combine that to make it work as a cmd?
to check is something is above for example 5 characters, is it len(thing) >= 5 or just thing >= 5
are you a beginner to python?
> 5
no need len?
>= checks if the obj is equal to or bigger than the obj
yeah
you need yes
no, i am using sublime text for first time so no working
in cmd store data to list and in on_message get it and send
what's the problem?
sublime bad ide tbh, no type-checkers/stuff that checks your code for bugs
Ok.
just use vsc
Reinstall discord.py
crashes
C:\Python37-32
also this ss
so you downloaded the discord py from the network
i downloaded it using
pip install discord
BRO
😱
you should do pip install discord.py
anything bad?

i had no idea or something but im sure you need to do discord.py
How can i fix this
if you have 10 dollars quit the fucking replit, turn to vps
I don't have 😦
ok then
Does someone know what happened here? The loop runs for a long time and all of a sudden I get this
But can you help me
for hell sake please learn py first before you start coding d.py
i cant spoonfeed you like a mother
I just use json.loads(response.text) for the api
can i have the code
Cant copy from phone. 1 sec
missing a :
k but i suggest you to code in pc or maybe get a keyboard for your phone
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
I do lol
your hand will be pain after a few coding
Just saw the error from the phone
def get_block():
response = requests.get("https://chain.so/api/v2/get_info/BTC")
data = json.loads(response.text)
block = data["data"]["blocks"]
return block
nope im bad on api and json stuff
ok
VSC doesn't even take that much ram
An electron app that doesn’t suck ram like a vacuum? Didn’t know those existed.
Ikrrrr
How to call bot on
yes
I was just joking kayle. Because they don’t exist.
VSC isn’t an ide
It’s a text editor.
How to make commands
in discord.py?
🙌 nvim
🗿
Yes
Emacs ❌
Text editor isn’t really a what’s better. It’s a what suits your needs and what’s more comfortable to you as a developer.
VSC can be an IDE or can be a regular text editor
That's the power that comes with extensions
Same with sublime, etc
Same with neovim, emacs etc
I beg to differ.
Idk why this happens, I leave my computer alone and the bot breaks. Only like half the commands work and idk why. I have not edited the code
How so? Does the built-in source control, or the built-in debugger stop VSC from being any less than an IDE? What about the linters, the type checkers? What about all the other things you could have on VSC?
What about the terminal? Does the built-in terminal make VSC stop before anything close to an IDE?
we can argue about it in #editors-ides in a sec Andy. I’m not willing to get slapped by a mod over a text editor/ide debate
Sure
So what you're trying to say is. After you leave your computer alone for a while half your commands stop working.
Yup
Is it really half or is it all of them.
Never seen that before.
New to python?
Or vs code

h
vsc is not really newbies friendly unlike pycharm, it's "supporting" you more in analyzing your code
Why do people feel the need to shill their favorite text editor and ide in here after seeing someone’s screen shotted code.
You have that backwards
cuz replit is gay
It’s an online ide
As long as he’s not trying to host his bot with it
It’s fine. He can write code where he wants
yes pls help me
learn python first
^
2 years != newbie
I need help with getting my discord bot to do something once a day
I want it to check the price of something
then send a message to the server if the price has dropped
every conditional has a colon at the end of the condition
you can use tasks
damm
lmao
You really called him the worst editor
reptile
lmao
Why you gotta be such a bully Ashley
😭 what'd I do
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
#bot-commands exists
is this right?
wha.....
ow ok
ghost ping 🥲
the alternative is sleeping so like
....smh
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.hug'):
await message.channel.send(random.choice(Picture)
if message.content.startswith('.kill'):
await message.channel.send(random.choice(Picture2)
!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.
is this right?
yeps
Can I have two logs (logging module) files for one code ?
well, at some point i was a newbie myself, indeed i had some headaches trying to understand how pycharm works, but eventually i got it, you can't avoid stuff just because it's hard, there are many useful tools in there that can help you at any level
but it said this File "main.py", line 25
if message.content.startswith('.hug'):
^
SyntaxError: invalid syntax
my head hurts after seeing such errors
Lol
With pycharm though you get like 50 different tools you never asked for, plus their type-checker is garbage. I'd rather get a fresh neovim config that I can soup up to do the same things pycharm does, except no bloat and with tools I actually use
Also no forced venv
first of all on_message commands are smh
then you dont know python, even more smh
now you're pasting code like text, thats really annoying
🤦♂️
rip me, I get too open about my thoughts
I use it cus I’ m familiar with it and I dont like vsc
When you're a beginner you're supposed to avoid things that’s hard so you can make your experience smooth. You work your way into harder things.
you should join the disnake server 👀
uhm, could you send the invite?
discord.gg/disnake is whitelisted :3
wow, it has a vanity url

🗿 imagine your server doesn't have a vanity, couldn't be me
alright, I'm poor to buy nitro, I just cant
^
make others buy nitro
^
how do you think you get boosts for the server
nah I dont like that too
why kill somebody off their money :)
just take their money
this is not advice, please do not do this
yeah
idk tho, tbh i never asked people to boost, sometimes ppl just join the server and be like "wow, this server nice" and boost even if they know no one in there lmao and i get confused bc i wouldn't waste my money on something i don't know nothing about
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
yes I'm definitely a human
my sleep schedule definitely proves that
!code
cring
from keep_alive import keep_alive
import discord
import os
import random
client = discord.Client()
Picture = ["nothing", "Hello"]
Picturetwo = ["yo", "hi"]
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.hug'):
await message.channel.send(random.choice(Picture))
if message.content.startswith('.kill'):
await message.channel.send(random.choice(Picturetwo))
keep_alive()
client.run(os.getenv('TOKEN'))
This code work but it didn't reply when i send the commands
!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.
and I would use process_commands at the end of your on message listener
!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.
https://vcokltfre.dev
Check out this tutorial
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
event, listeners dont need to process commands ^^
def setup_logger(name, log_file, level=logging.WARNING):
handler = logging.FileHandler(log_file)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
on_command_logs = setup_logger('on_command', 'on_commands.log')
command_errors = setup_logger('command errors', 'on_command_errors.log')
@bot.event
async def on_command_error(error):
command_errors.warning('A command has errord')
Anyone mind telling me why on_command_error doesn't write into the logs file
what?
u do know that the on_command_error func takes two args, right?
logger.setLevel
🗿
what does it take?
ctx, error
ctx, error?
Yea
wait it does?
yeah
smh
okay nvm it does
not even commands.on_command_error
weird
it should be this ^ no idea why it's not working (discord.on_command_error)
idk
discord.ext.commands.Bot.on_command_error
!d discord.ext.commands.Bot.on_command_error
!d discord.ext.commands.Bot.on_command_error
Wait what tf
see the second one lol
yeah
just discord.py things
The first one is used inside the bot object when you subclass it iirc 🏃
well, all instances of it
but the second one is an event reference except idk why it's under the main lib
how to add oop to content message properly
I mean the event is usable without the event/listen decorator```py
class MyBot(Bot):
def init(self):
...
async def on_command_error(self, context,error):
...
Wdym by adding OOP?
like adding variables
message.somethingextralikethisorjustnameitcanalsobeafunction = "yes"
?
I rename it to _on_command_error 🗿
so how to add it on a bot message
Will raise an attribute error
hmm
setattr fails too
?
eh?
!e ```py
class Object:
pass
a = Object()
a.somefield = "value"
print(a.somefield)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
value
Idk mate why don't you try with some message object
Because Message is slotted
Pass the variable.
I see, but subclassing the Context.message would allow adding attribute in init dunder or a property right?
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
Sure, if you subclass it you can do pretty much anything
!botvar same as your code
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!
How do i attach embed to bot's response?
like a reply?
yeah
make an embed and then reply(embed=embed)
i knoww but how do i make an embed?
JSON data?
why u used one string at variable ( ' ' )
and if heistar == "": (double string)
what's the traceback
btw
oh yeah i had this problem with my bots alot of times, idk why that not working
heistar is a private variable dude, wait no it isnt
good practice, kick mee6 and dyno from your servers
@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")
its alright, welp
just make the server bot-less
Will be fun to see what happens when every mod goes to sleep or is AFK 👀
no bot is good enough to self-moderate a server anyways
nor can it be
At least it can prevent spam and delete messages with banned words
well it can, but imagine, I'm in a server with more than 400k members (with only 1 bot) and all the bot does is handle reports and kick/ban/warn and send dms to members on command, like ew bot
Hmmm, SUPER under utilized
and they complain that trolls are increasing everyday ;-;
like what
Lmaoo
false, i've just finished my automod bot, detects scam links, banned words, accounts created too recents are banned
it's easy to set up a good moderation bot if it's just for one guild
Lmao
and that is what is called a waste of time ffs
You can add something which bans users with pycord or in their status or aboutme too
lol
Rip someone who created a discord account just to join a support server for help
Bots can't access About Me's, forgot?
oh true
andy
Collectors hmm
How's rin doing?
My motivation is wilting
the measures are just for my main server, for the support server i don't have those kekw, since my attention is to moderate my public server mainly
Hold on to it!
btw, how many choices can a parameter take in slashes?
it's not waste of time tho, you always learn new stuff by expanding your filed of knowledge
what would a snipe command do exactly?
well, cant argue
infinite? read the docs
catch the deleted message
too lazy, search and tell, pleeeeaseee hun
from a certain user, or message id?
discord doesn't like it, but shows the latest deleted message
'ight imma not
S. M. H.
don't want bring down the gods wrath on me
Alters according to developer's choice
thanks
for what?
Okay, it doesn't say anything in developer docs, afais
yeah
though how could you use snipe with a message id, you can't copy the id if the message is deleted
unless your on_message_delete triggers and send the message with the id on a log channel

im still confused on the usage of a snipe command
Then why did u tell me to check 🤦
It gets the last deleted message
on channel or guild?
channel
nvm, another issue
both
depends on you
Mind explaining or u want me to read it from yr brain?
I should be paying attention to geography but what kind of game dev needs to know geography on their resume?
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
please
i forgot, i'll tell if i remember
🗿 general culture. you need it
whyudothistomeeverytime😭
I'd be glad if you accept my apologies, hun
argh
@slate swan mind seeing #ot0-psvm’s-eternal-disapproval and telling your answer? 👀
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
help anyone?
i made a basic ship command
which works fine
but im trying to rig it so if my friend and his crush are shipped then it defaults to 100%
My Lack of Understanding prohibits me from understand that
that doesnt seem to work tho
lmaoooooooooo
i have to finish it before his crush comes back home from vacation ;/
and i cant figure out whats wrong
rip lemme check
thanks 🙏
tbh, thats really such a long ship command, you didnt have to make it that long ;-;
yeah i needed to add gifs to the embed too ;/
and since i set the embed values before i make the embed
and the gif after i make it
that complicates things
okay I'm having a stroke trying to understand
lmao
You want to play skribbl?
cant rn, got an important call which I cant miss so, later, I'm sorry
Okay
outermost if statement checks if the 2 people mentioned are my friend and his crush
if it isnt it runs like normal
check that at first, easiest way
then return the send method
yeah i did
if (
768393728163053619 not in (person1.id, person2.id)
and 536479129025904651 not in (person1.id, person2.id)
):
imagine, just tell your friend to tell her that he loves her, save the pain
plus its a lot more realistic
"thee"
reptilian Shakespeare?
yeah im using async functions and await in my code
lmao
i get how that works
and i already have decorators for limiting commands to people with certain perms
im not at home and on a shit laptop that takes like 5 seconds to register text
so its a bit hard to debug
@maiden fable choices can only take 25 fields 😔
Oh cool
Reptilian 
wait, i didnt know it yerlikaya 😔
check who executed the command and who the author is
"who executed the command" and "author" means the same thing
@regal pulsar
if person1.id in [friendsid, crushid]:
if person2.id in [friendsid, crushid]:
ship_percent == 101
right
😭 They don't understand, I just told them to tell their friend that he loves her, that's more real
use discord bot rng to your advantage
😈
imagine the bot malfunctioning and sending 0 percent
does anyone have any idea for a currency bot
no
no
caeeedennn
ahsleytyyy
LOL
lmao
if person1.id in [friendsid, crushid]:
if person2.id in [friendsid, crushid]:
ship_percent == 101
@slate swan fixed it i think
idk why the args are person1 and person2
confusing asf
TypeError: Errors.on_slash_command_error() takes 2 positional arguments but 3 were given
how are you
does your stupidity really cut out the part where its your problem, at least tell the error
you arent in a cog?
I'm fine, and you?
ruined
no im in cog
not too bad
try typehinting
i have an idea
i want to make an "error log"
but should i
bc its rlly easy
but idk if its a good idea
@slate swan
like when an error goes off
it gets logged to a file with the error, error message, and time the error was called
and then ppl in the owner ids can check it
why isn't that a good idea, I have it
then do it
well its easy af, and I dont see a downside of that, so, just make it, would be helpful
the war has begun 😦
but should i log it in a json file for later use, or just send it to a specific channel so i can see it
@stray carbonconverrt message to lower chars
send it to a channel and store it too
string.content.lower().contains
string.content?
message
@slate swan i have an idea
cz it is required?
its just example of what datatype
?
ashley this message
string.lower()
str().lower()
"hellO".lower()
and this message, are both inappropriate and break our rules
str is an object itself mate
You don't need to create an instance
@slate swan should i format it like
{
"errormessagehere": "timeoferror"
}
oh well that way
@slate swanlol am just giving examples of .lower()
right, you can make an instance
ah gotcha
@merry charmif u want a dict yes
@slate swancause i said string.lower() and he thought he should type string.lower("H3Lo")
Sidenote: instead of saving the time as a string you may utilise the datetime library to save a datetime object
Yea I understand
@daring olivehand out a warning!
but i could sort it by time if i go
{
"time": "errormsg"
}
well its key,value so
we don't moderate on command ;)
tsss you could be equal tho
How to reset the value of a variable? sql
he asked nicely :p
i need to get est though, i will use datetime, just its always in utc and i dont understand it
kappa
!d datetime.datetime.estnow
No documentation found for the requested symbol.
huh? you mean replace a value in a row?
1 moment
!d datetime.datetime.now
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
1 minute I'll be right back
@honest vessel will this work? datetime.datetime.est.now()
!e
import datetime
print(datetime.datetime.est.now())
@honest vessel :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: type object 'datetime.datetime' has no attribute 'est'. Did you mean: 'dst'?
full code will probably be something like this ```py
with open("json/errorlog.json", "r") as f:
errors = json.load(f)
with open("json/errorlog.json", "w") as f:
errors[str(error)] = datetime.datetime.est.now()
json.dump(errors, f, indent=2)
!e ```py
import datetime
print(datetime.datetime.est.now())
@merry charm :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: type object 'datetime.datetime' has no attribute 'est'. Did you mean: 'dst'?
!e ```py
import datetime
print(datetime.datetime.dst.now())
@merry charm :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'method_descriptor' object has no attribute 'now'
thats weird
u just want datetime of now?
in est, yea
what is est?
oh
When the warnas reach 3/3, it is necessary that the variable be reset, and on a new
!e py from datetime import datetime, timezone print(datetime.now(timezone("US/Eastern)))
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: type object 'datetime.timezone' has no attribute 'est'. Did you mean: 'dst'?
Est doesn't seem like an available timezone, could you see if it's called something else too?
with open("json/errorlog.json", "r") as f:
errors = json.load(f)
with open("json/errorlog.json", "w") as f:
errors[str(error)] = datetime.datetime.est.now()
json.dump(errors, f, indent=2)
channel = bot.get_channel(931055707959197710)
erroremb = discord.Embed(
title = f"Error called in {ctx.guild.name}!",
description = f"Error Below!\n`error`",
color = discord.Color.red()
)
erroremb.set_footer(text=f"Error called by {ctx.author}", icon_url=ctx.author.avatar_url)
await channel.send(embed=erroremb)
finished
just need datetime fixed and were good
!e ```py
import datetime
print(datetime.datetime.now())
@merry charm :white_check_mark: Your eval job has completed with return code 0.
2022-02-24 15:34:24.995506
I want convert GMT time to EST time and get a timestamp. I tried the following but don't know how to set time zone.
time = "Tue, 12 Jun 2012 14:03:10 GMT"
timestamp2 = time.mktime(time.st...
ok thats probably fine
See the 1st answer
note: avatar_url was changed in 2.0
yeah ive tried that
didnt work?
nope
You wanna make sure that the ship is 100%?
i wanna make the ship 100% if my friend and his crush are the ones being shipped
ill send updated ver i changed some stuff
alr
ship = # for othrs
them = [ your_friend_id, crush_id]
if person1.id in them and person2.id in them:
ship = 100
``` 🏃
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ive tried every possible thing i could think of to compare the two
^
should i save the datetime as an interger or a string
hmm i think ive tried it
@slate swan
but ill try again
Just save the object itself
and change it when you send it
kk
