I was wondering how it is possible to get a bot status to switch
please help me because I'm new to coding discord bots and I don't know much and when I google it it doesn't work for me.
This is my code:
import keep_alive
import discord, os
from discord.ext import commands
import typing
import asyncio
import random
prefix="cs!"
client = commands.Bot(command_prefix=prefix)
def replaceSpaces(string):
string = string.strip()
i = len(string)
space_count = string.count(' ')
new_length = i + space_count * 2
if new_length > 1000:
return -1
index = new_length - 1
string = list(string)
for f in range(i - 2, new_length - 2):
string.append('0')
for j in range(i - 1, 0, -1):
if string[j] == ' ':
string[index] = '0'
string[index - 1] = '2'
string[index - 2] = '%'
index = index - 3
else:
string[index] = string[j]
index -= 1
return ''.join(string)
#client.event
async def on_ready():
await client.change_presence(activity=discord.Game(name="cs!help || made with <3 by Spoon#7194"))
#client.event
async def on_ready():
servers = len(client.guilds)
members = 0
for guild in client.guilds:
members += guild.member_count - 1
await client.change_presence(activity = discord.Activity(
type = discord.ActivityType.watching,
name = f'cs!help | {servers} Server {members} Member'
))
#client.event
async def on_message(message):
msg = message.content.lower()
if message.author == client.user:
return
elif msg.startswith("cs!hello"):
await message.channel.send(f"hello, {message.author}!")
elif msg.startswith("cs!help"):
await message.channel.send(f"commands: cs!hello, cs!replsearch <query>, cs!twitch <query>, cs!youtube <query>, cs!google <query>")
elif msg.startswith("cs!replsearch "):
resultr = msg.split('cs!replsearch ', 1)
if resultr[-1] == "":
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
elif msg.startswith("cs!replsearch"):
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
elif msg.startswith("cs!twitch "):
resultt = msg.split('cs!twitch ', 1)
if resultt[-1] == "":
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
else:
await message.channel.send(f"https://twitch.tv/search?term={replaceSpaces(resultt[-1])}")
elif msg.startswith("cs!twitch"):
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
elif msg.startswith("cs!youtube "):
resulty = msg.split('cs!youtube ', 1)
if resulty[-1] == "":
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
else:
await message.channel.send(f"https://www.youtube.com/results?search_query={replaceSpaces(resulty[-1])}")
elif msg.startswith("cs!youtube"):
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
elif msg.startswith("cs!google "):
result = msg.split('cs!google ', 1)
if result[-1] == "":
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
else:
await message.channel.send(f"https://www.google.com/search?q={replaceSpaces(result[-1])}")
elif msg.startswith("cs!google"):
await message.channel.send("Error :face_with_raised_eyebrow:, no query given")
elif msg.startswith("cs!"):
await message.channel.send("Error :face_with_raised_eyebrow:, not a valid command")
#server.server()#bot.command()
#async def token
#embed=discord.Embed(title="Help", description="description here")
#embed.add_field(name="Moderation commands", value="your commands here", inline=False)
#embed.add_field(name="Fun Commands", value="your commands here", inline=False)
#embed.set_footer(text="footer text")
#await ctx.send(embed=embed)
keep_alive.keep_alive()
client.run('{I deleted this part here}')
Change Your Status every x seconds
#discord.ext.tasks.loop(seconds=5)
async def change_p():
await client.wait_until_ready()
statuses = [f"{len(client.guilds)} Servers with {len(client.users)} Users!", "You Talk!",
"The Epic Server!"]
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=choice(statuses)))
change_p.start()
const status = "YOURSTATUS"
client.user.setActivity(status)
Also Try that :)
Related
trying to make a nice embed for my diceroll command to output to but my issue is that the embed keeps just displaying raw value rather than the int value i'm trying to get (image for reference bellow) i’ve tried to find workarounds or solutions online but cant find anything that works or is specific to my issue
#bot.command()
async def rolldice(ctx):
messagetwo = await ctx.send("Choose a number:\n**4**, **6**, **8**, **10**, **12**, **20** ")
user = ctx.message.author.display_name
def check(m):
return m.author == ctx.author
try:
messageone = await bot.wait_for("message", check = check, timeout = 30.0)
m = messageone.content
if m != "4" and m != "6" and m != "8" and m != "10" and m != "12" and m != "20":
await ctx.send("Sorry, invalid choice.")
return
coming = await ctx.send("Here it comes...")
asyncio.sleep(1)
await coming.delete()
await messagetwo.delete()
await ctx.channel.purge(limit=2)
embedVar = discord.Embed(title="{user}'s Dice",color=0x00ffff)
embedVar.add_field(name="rolled", value="D{m}", inline=True)
embedVar.add_field(name="landed", value="{random.randint(1, int(m))}", inline=True)
embedVar.set_footer(text='Booty Police | Dungeon Dice',icon_url="http://canvaswrite.com/PI/pybot/attachments/server-icon-full.png")
await ctx.send(embed=embedVar)
await ctx.send(f"{user} rolled a **D{m}** and got a **{random.randint(1, int(m))}**")
except asyncio.TimeoutError:
await messageone.delete()
await ctx.send("Procces has been canceled because you didn't respond in **30** seconds.")
I think you are trying to use f-string but forgot to place the f before the string. Without the f it will not format the string. Here's a guide on f-strings if you want to read more about them
x = 3
print(f"This is the value {x}")
>>> This is the value 3
so in order for your code to work you need to just prepend the string with an f. the fixed code would look something like this:
#bot.command()
async def rolldice(ctx):
messagetwo = await ctx.send("Choose a number:\n**4**, **6**, **8**, **10**, **12**, **20** ")
user = ctx.message.author.display_name
def check(m):
return m.author == ctx.author
try:
messageone = await bot.wait_for("message", check = check, timeout = 30.0)
m = messageone.content
if m != "4" and m != "6" and m != "8" and m != "10" and m != "12" and m != "20":
await ctx.send("Sorry, invalid choice.")
return
coming = await ctx.send("Here it comes...")
asyncio.sleep(1)
await coming.delete()
await messagetwo.delete()
await ctx.channel.purge(limit=2)
embedVar = discord.Embed(title=f"{user}'s Dice",color=0x00ffff)
embedVar.add_field(name="rolled", value=f"D{m}", inline=True)
embedVar.add_field(name="landed", value=f"{random.randint(1, int(m))}", inline=True)
embedVar.set_footer(text='Booty Police | Dungeon Dice',icon_url="http://canvaswrite.com/PI/pybot/attachments/server-icon-full.png")
await ctx.send(embed=embedVar)
await ctx.send(f"{user} rolled a **D{m}** and got a **{random.randint(1, int(m))}**")
except asyncio.TimeoutError:
await messageone.delete()
await ctx.send("Procces has been canceled because you didn't respond in **30** seconds.")
Sorry if this is a dumb question, however whenever I'm running my code it does not listen to the if statements within the if statement?
#bot.command()
#commands.has_role('Moderator')
async def activity(ctx):
days = datetime.datetime.now() - datetime.timedelta(days=7)
print(days)
for member in ctx.guild.members:
for role in member.roles:
if role.name == "Trusted Member":
if role.name == "Exempt":
print("<#" + str(member.id) + "> has a perm exemption")
elif role.name == "Temp Exempt":
print("<#" + str(member.id) + "> has a temp exemption, it has now been removed...")
else:
counter = 0
channel = bot.get_channel(1)
async for message in channel.history(limit=None, after=days):
if message.author == member:
counter += 1
print("<#" + str(member.id) + "> has sent " + str(counter))
The script will not check if they have an exempt role and instead just proceed to check how many messages they have sent.
Thanks in advance.
Working solution I found with help thanks to Rani
#bot.command()
#commands.has_role('Moderator')
async def activity(ctx):
days = datetime.datetime.now() - datetime.timedelta(days=7)
for member in ctx.guild.members:
role_names = []
for role in member.roles:
role_names.append(role.name)
if "Trusted Member" in role_names:
if "Exempt" in role_names:
print("<#" + str(member.id) + "> has a perm exemption")
elif "Temp Exempt" in role_names:
print("<#" + str(member.id) + "> has a temp exemption, it has now been removed...")
else:
counter = 0
channel = bot.get_channel(1)
async for message in channel.history(limit=None, after=days):
if message.author == member:
counter += 1
print("<#" + str(member.id) + "> has sent " + str(counter))```
What I'm Trying to do: Make a hangman game using discord.py-rewrite
My Problem: The code stops working after the bot sends (Fruits Category) or (Animals Category) etc. There are no error messages either. I've tried changing def to async def to try to use await ctx.send, but to no avail.
#client.command()
async def hangman(ctx, category):
fruits = ['pear', 'banana', 'apple']
animals = ['cat', 'horse', 'turtle']
userGuesslist = []
userGuesses = []
playGame = True
category = category
continueGame = "Y"
name = ctx.message.author.mention
await ctx.send(f"Welcome to hangman {name}!")
time.sleep(2)
await ctx.send("Your Objective:tm:: Find my secret word from the category you chose")
time.sleep(2)
await ctx.send("Don't forget that you can only guess with letters!")
time.sleep(2)
await ctx.send(f"Good luck {name}!")
while True:
while True:
if category.upper() == 'F':
await ctx.send("__**Fruits Category**__")
secretWord = random.choice(fruits)
break
elif category.upper() == 'A':
await ctx.send("__**Animals Category**__")
secretWord = random.choice(animals)
break
else:
await ctx.send("__**Random Category**__")
secretWord = random.choice(fruits, animals)
break
if playGame:
secretWordList = list(secretWord)
attempts = (len(secretWord) + 2)
def pGuessedLetter():
("Your Secret word is: "+ ''.join(userGuessList))
for n in secretWordList:
userGuesslits.append('\_ ')
pGuessedLetter()
await ctx.send(f"Number of allowed guesses for this word: {attempts}")
while True:
await ctx.send("**Guess a letter:**")
def check(m):
return m.content and user == ctx.message.author
letter = check
if letter in userGuesses:
await ctx.send("You already guessed this letter, try something else")
else:
attempts -= 1
userGuesses.append(letter)
if letter in secretWordList:
await ctx.send("Nice guess!")
if attemps > 0:
await ctt.send(f"Attempts left: {attempts}")
for i in range(len(secretWordList)):
if letter == secretWordList[i]:
letterIndex = i
userGuesslits[letterIndex] = letter.upper()
pGuessedLetter()
else:
await ctx.send("Nope, try again :eye: :eye:")
if attempts > 0:
await ctx.send(f"Attempts left: {attempts}")
pGuessedLetter()
joinedList = ''.join(userGuesslist)
if joinedList.upper() == secretWord.upper():
await ctx.send(f"You got it {name}! The word was {secretWord}")
break
elif attempts == 0:
await ctx.send(f"Too many Guesses! Better luck next time {name}")
await ctx.send(f"The secret word was {secretWord.upper()}")
break
#hangman.error
async def hangman_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):
await ctx.send("""Ensure you include a category:
**Example:** `bl!hangman A`
`F - Fruits`
`A - Animals`
`X - Cancel`
""")
I wouldn't recommend to use while loops!
Use await client.wait_for('message') instead. (https://discordpy.readthedocs.io/en/latest/api.html?highlight=wait_for#discord.Client.wait_for)
I have a python discord bot and I need it to get user input after a command, how can I do this? I am new to python and making discord bots. Here is my code:
import discord, datetime, time
from discord.ext import commands
from datetime import date, datetime
prefix = "!!"
client = commands.Bot(command_prefix=prefix, case_insensitive=True)
times_used = 0
#client.event
async def on_ready():
print(f"I am ready to go - {client.user.name}")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{client.command_prefix}python_help. This bot is made by drakeerv."))
#client.command(name="ping")
async def _ping(ctx):
global times_used
await ctx.send(f"Ping: {client.latency}")
times_used = times_used + 1
#client.command(name="time")
async def _time(ctx):
global times_used
from datetime import date, datetime
now = datetime.now()
if (now.strftime("%H") <= "12"):
am_pm = "AM"
else:
am_pm = "PM"
datetime = now.strftime("%m/%d/%Y, %I:%M")
await ctx.send("Current Time:" + ' ' + datetime + ' ' + am_pm)
times_used = times_used + 1
#client.command(name="times_used")
async def _used(ctx):
global times_used
await ctx.send(f"Times used since last reboot:" + ' ' + str(times_used))
times_used = times_used + 1
#client.command(name="command") #THIS LINE
async def _command(ctx):
global times_used
await ctx.send(f"y or n")
times_used = times_used + 1
#client.command(name="python_help")
async def _python_help(ctx):
global times_used
msg = '\r\n'.join(["!!help: returns all of the commands and what they do.",
"!!time: returns the current time.",
"!!ping: returns the ping to the server."])
await ctx.send(msg)
times_used = times_used + 1
client.run("token")
I am using python version 3.8.3. I have already looked at other posts but they did not answer my question or gave me errors. Any help would be greatly appreciated!
You'll be wanting to use Client.wait_for():
#client.command(name="command")
async def _command(ctx):
global times_used
await ctx.send(f"y or n")
# This will make sure that the response will only be registered if the following
# conditions are met:
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower() in ["y", "n"]
msg = await client.wait_for("message", check=check)
if msg.content.lower() == "y":
await ctx.send("You said yes!")
else:
await ctx.send("You said no!")
times_used = times_used + 1
And with a timeout:
import asyncio # To get the exception
#client.command(...)
async def _command(ctx):
# code
try:
msg = await client.wait_for("message", check=check, timeout=30) # 30 seconds to reply
except asyncio.TimeoutError:
await ctx.send("Sorry, you didn't reply in time!")
References:
Client.wait_for() - More examples in here
Message.author
Message.channel
Message.content
asyncio.TimeoutError
With this you can make something like this
#client.command()
async def command(ctx):
computer = random.randint(1, 10)
await ctx.send('Guess my number')
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
msg = await client.wait_for("message", check=check)
if int(msg.content) == computer:
await ctx.send("Correct")
else:
await ctx.send(f"Nope it was {computer}")
I've had a few days on trying to figure that out, and the only thing that was simple for me was storing the message.content into a list and using it later.
some_list = []
user_message = message.content.split()
some_list.append(user_message)
and since I am using commands I wanted to remove that '!' and get the raw message
for i in some_list:
del i[0]# delete's command tag
I have a Discord bot that stores a deadline for a user in a message channel. After the deadline ends, I want the bot to notify the moderators so they can deal with it.
Everything for the bot besides that is already done. My idea for this issue is to just have a function that checks the channel with deadlines every 24 hours and finds the same date on it as the current date and takes out the userid (which is also stored in said message).
I'm open to other solutions for this problem.
I've read up and Googled a bunch. It, at least, seems like to me that time.sleep() and schedule.every will stop my whole program for that time, but maybe I'm wrong about the schedule thing, because I tried to implement it into my code, but I got no idea how to make it work. I have only a week of Python experience here, bear with me.
Here is pretty much my whole code if it helps (without the bot token part, of course)
import datetime
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
from discord.utils import get
from datetime import datetime, timedelta
Client = discord.client
client = commands.Bot(command_prefix = '%')
Clientdiscord = discord.Client()
#client.event
async def on_ready():
await client.change_presence(game=Game(name='with nuclear waste'))
print('Ready, bitch')
#client.event
async def on_reaction_add(reaction, user):
if ' has sent an application to become a full fledged FRICK' in reaction.message.content:
Name = reaction.message.content.split('#')
usid = reaction.message.content.split('=')
usid1 = usid[1].split(' ')
user =reaction.message.server.get_member(usid1[0])
msg = reaction.message.content.split('?')
eventcode = str (msg[1])
cont = str(msg[0])
kakapoopoo = '#' + usid1[0]
#await client.send_message(user, 'test')
if reaction.emoji == get(client.get_all_emojis(), name='FeelsBadMan'):
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 1 event.')
await client.edit_message(reaction.message, cont + '?01')
if reaction.emoji == get(client.get_all_emojis(), name='veetsmug'):
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 2 events.')
await client.edit_message(reaction.message, cont + '?10')
if reaction.emoji == get(client.get_all_emojis(), name='POGGERS'):
await client.edit_message(reaction.message, cont + '?11')
await client.send_message(client.get_channel('560678137630031872'), Name[0] + ' has attented 3 events.')
if reaction.emoji == get(client.get_all_emojis(), name='HYPERS'):
role1 = discord.utils.get(reaction.message.server.roles, name='Pending Frick')
await client.remove_roles(user, role1)
await client.send_message(client.get_channel('560678137630031872'), user.mention + ' has attented 4 events and is now a ***FRICK***.\n#here')
role2 = discord.utils.get(reaction.message.server.roles, id='561087733834186754')
await client.add_roles(user, role2)
await client.send_message(user, 'You are now a full fledged ***FRICK***')
await client.delete_message(reaction.message)
elif 'To approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:' in reaction.message.content:
cunt = reaction.message.content.split('#')
name = cunt[0]
idududu = reaction.message.content.split('?')
peepee = idududu[1]
#await client.send_message(client.get_channel('560678137630031872'), 'test' + peepee)
idud = peepee.split('\nThe events the user has attented before are:')
usid = idud[0]
#await client.send_message(client.get_channel('560678137630031872'), 'test' + usid)
#await client.send_message(client.get_channel('560678137630031872'), 'test' +str(usid))
user=await client.get_user_info(usid)
event = reaction.message.content.split('has attented a ')
eventu = event[1]
evento = eventu.split('Screenshot:')
if reaction.emoji == get(client.get_all_emojis(), name='HYPERS'):
await client.send_message(user, 'Your screenshot has been approved')
await client.delete_message(reaction.message)
async for message in client.logs_from(discord.Object(id='561667365927124992'), limit = 100):
#await client.send_message(user, 'test')
if name in message.content:
if ' eventcode?00' in message.content:
await client.send_message(user, 'You have attented 1 event')
emoji = get(client.get_all_emojis(), name='FeelsBadMan')
await client.add_reaction(message, emoji)
await client.send_message(discord.Object(id='562607755358371840'), str(usid) + ' ' + str(evento[0]))
elif ' eventcode?01' in message.content:
await client.send_message(user, 'You have attented 2 events')
emoji = get(client.get_all_emojis(), name='veetsmug')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
cont = message.content
await client.edit_message(message, cont + ', ' + str(evento[0]))
elif ' eventcode?10' in message.content:
await client.send_message(user, 'You have attented 3 events')
emoji = get(client.get_all_emojis(), name='POGGERS')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
cont = message.content
await client.edit_message(message, cont + ', ' + str(evento[0]))
elif ' eventcode?11' in message.content:
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if usid in message.content:
await client.delete_message(message)
elif reaction.emoji == get(client.get_all_emojis(), name='FeelsBadMan'):
await client.send_message(user, 'Your screenshot has not been approved')
await client.delete_message(reaction.message)
#client.event
async def on_message(message):
if message.content == '%start':
if "561047714230435871" in [role.id for role in message.author.roles]:
deadline = datetime.now() + timedelta(days=21)
author = message.author
mes = str(author) + ' has sent an application to become a full fledged FRICK id ='+ str(message.author.id) + ' Deadline+' +str(deadline.strftime("%Y-%m-%d")) + ' eventcode?00'
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
role = get(message.server.roles, id='561055432748302336')
await client.add_roles(message.author, role)
await client.send_message(client.get_channel('561667365927124992'), mes)
await client.send_message(message.author, '***You have entered the Frickling program!**\n\nTo become a full fledged Frick you must attend 4 guild/alliance events. Please provide screensots to the bot proving that you have attented them by using %attended command followed by a screenshot **LINK** and the name of the activity.\n\n Example: %attented https://cdn.discordapp.com/attachments/530909412320083969/558085258164305921/guild_event_2.jpg fame farm')
role = get(message.server.roles, name='Frickling')
await client.remove_roles(message.author, role)
elif "561055432748302336" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'Seems like you already started the application process for becoming a full fledged Frick')
else:
await client.send_message(message.channel,'Seems like you do not have the permisssions to use me.\n\nIt might be because your application for Frickling has not yet been approved or you are already a full fledged Frick')
elif message.content == 'Tell that bot to get lost':
if message.author == message.server.get_member('336858563064496130'):
await client.send_message(message.channel,'Get lost, stupid bot')
elif message.content == 'Tell Meatcup to get lost':
if message.author == message.server.get_member('336858563064496130'):
user = discord.utils.get(reaction.message.server.members, id ='331864154803666945')
await client.send_message(user, 'Get lost, Meatcup')
elif message.content == '%cunt':
await client.send_message(message.channel,'Yes, my master?')
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
elif message.content == '%testfrick':
if "561087733834186754" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'You are a frick')
else:
await client.send_message(message.channel,'Error')
elif message.content == '%testpend':
if "561055432748302336" in [role.id for role in message.author.roles]:
await client.send_message(message.channel,'You are pending')
else:
await client.send_message(message.channel,'Error')
elif '%attended' in message.content and message.author.id != '560634369094582302':
author = message.author
authid = message.author.id
cunt = 0
msg = message.content.split(' ',2)
if len(msg) > 2:
emoji = get(client.get_all_emojis(), name='HYPERS')
await client.add_reaction(message, emoji)
for i in client.servers:
for x in i.roles:
if x.id == '561055432748302336':
async for message in client.logs_from(discord.Object(id='562607755358371840'), limit = 100):
if authid in message.content:
eventu = message.content.split(' ',1)
cunt = 1
await client.send_message(discord.Object(id='560679934209687552'), str(author) + ' has attented a ' + msg[2] + '\nScreenshot:' + msg[1] + '\nTo approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:\nUserid?'+authid + '\nThe events the user has attented before are: ' + str(eventu[1]))
if cunt == 0:
await client.send_message(discord.Object(id='560679934209687552'), str(author) + ' has attented a ' + msg[2] + '\nScreenshot:' + msg[1] + '\nTo approve screenshot react with :HYPERS: to dissaprove react with :FeelsBadMan:\nUserid?'+ authid)
else:
await client.send_message(message.author,'Error. You did not provide the name of the event or you only provided the name of the event.')
For asynchronous python, when non-blocking sleeping is required, you can use the method asyncio.sleep(n), n being the number of seconds you want the method to sleep for. So a basic async method that sleeps once every 24 hours would look something like this:
async def daily_task():
print('This method will NOT block')
await asyncio.sleep(24*60*60)
EDIT: Thanks go to Benjin, who pointed out that I forgot to await the sleep.
Threads will let you work "simultaneously" on 2 things (or more...). When one thread will sleep, another thread can do "the rest"