DISCORD.PY
I try to create an command for a poll system and encounter a problem. Command is as follows:
#commands.command(pass_context = True)
async def poll(self, ctx, question, *options: str):
author = ctx.message.author
server = ctx.message.server
if not author.server_permissions.manage_messages: return await self.bot.say(DISCORD_SERVER_ERROR_MSG)
if len(options) <= 1:
await self.bot.say("```Error! A poll must have more than one option.```")
return
if len(options) > 2:
await self.bot.say("```Error! Poll can have no more than two options.```")
return
if len(options) == 2 and options[0] == "yes" and options[1] == "no":
reactions = ['š', 'š']
else:
reactions = ['š', 'š']
description = []
for x, option in enumerate(options):
description += '\n {} {}'.format(reactions[x], option)
embed = discord.Embed(title = question, color = 3553599, description = ''.join(description))
react_message = await self.bot.say(embed = embed)
for reaction in reactions[:len(options)]:
await self.bot.add_reaction(react_message, reaction)
embed.set_footer(text='Poll ID: {}'.format(react_message.id))
await self.bot.edit_message(react_message, embed=embed)
My question is: How can I make the question I ask using the command to have more words. If I use more words now, I read them as options and get an error.
Ex 1: /poll You are human yes no (only read "you" as a question, and the rest are options.)
Ex 2: /poll You are human yes no (that's what I want)
Thank you!
When calling the command, putting a string in quotes will cause it to be treated as one argument:
/poll "You are human" yes no
You can do:
#bot.command()
async def poll(ctx, question, option1=None, option2=None):
if option1==None and option2==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**ā
= Yes**\n**ā = No**")
await message.add_reaction('ā')
await message.add_reaction('ā
')
elif option1==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**ā
= {option1}**\n**ā = No**")
await message.add_reaction('ā')
await message.add_reaction('ā
')
elif option2==None:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**ā
= Yes**\n**ā = {option2}**")
await message.add_reaction('ā')
await message.add_reaction('ā
')
else:
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \n{question}```\n**ā
= {option1}**\n**ā = {option2}**")
await message.add_reaction('ā')
await message.add_reaction('ā
')
but now you must do /poll hello-everyone text text
if you want to to not have the "-" you must do:
#bot.command()
async def poll(ctx, *, question):
await ctx.channel.purge(limit=1)
message = await ctx.send(f"```New poll: \nā
= Yes**\n**ā = No**")
await message.add_reaction('ā')
await message.add_reaction('ā
')
But in this one you can't have your own options...
use :
/poll "You are human" yes no
here, "You are human" is one string "yes" "no" are other two strings.
another better way to do it is:
#commands.command(pass_context = True)
async def poll(self, ctx, option1: str, option2: str, *, question):
or, you can use wait_for
#commands.command(pass_context = True)
async def poll(self, ctx, *options: str):
...
question = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
...
it is working
#commands.has_permissions(manage_messages=True)
#commands.command(pass_context=True)
async def poll(self, ctx, question, *options: str):
if len(options) > 2:
await ctx.send('```Error! Syntax = [~poll "question" "option1" "option2"] ```')
return
if len(options) == 2 and options[0] == "yes" and options[1] == "no":
reactions = ['š', 'š']
else:
reactions = ['š', 'š']
description = []
for x, option in enumerate(options):
description += '\n {} {}'.format(reactions[x], option)
poll_embed = discord.Embed(title=question, color=0x31FF00, description=''.join(description))
react_message = await ctx.send(embed=poll_embed)
for reaction in reactions[:len(options)]:
await react_message.add_reaction(reaction)
#create a yes/no poll
#bot.command()
#the content will contain the question, which must be answerable with yes or no in order to make sense
async def pollYN(ctx, *, content:str):
print("Creating yes/no poll...")
#create the embed file
embed=discord.Embed(title=f"{content}", description="React to this message with ā
for yes, ā for no.", color=0xd10a07)
#set the author and icon
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
print("Embed created")
#send the embed
message = await ctx.channel.send(embed=embed)
#add the reactions
await message.add_reaction("ā
")
await message.add_reaction("ā")
for your code to treat the text in the user's message as one string, use "content:str" in your command arguments
I know my code isn't very dynamic and pretty but i did that and it's functional.
#client.command()
async def poll(ctx):
options = ['1ļøā£ Yes Or No', '2ļøā£ Multiple Choice']
embed = discord.Embed(title="What type of poll you want ?" , description="\n".join(options), color=0x00ff00)
msg_embed = await ctx.send(embed=embed)
reaction = await client.wait_for("reaction_add", check=poll)
if (reaction[0].emoji == '1ļøā£'):
user = await client.fetch_user(ctx.author.id)
msg = await user.send("What is your question ?")
question = await client.wait_for("message", check=lambda m: m.author == ctx.author)
answers = ['\n\u2705 Yes\n', '\u274C No']
new_embed = discord.Embed(title="Poll : " + question.content, description="\n".join(answers), color=0x00ff00)
await msg_embed.edit(embed=new_embed)
await msg_embed.remove_reaction('1ļøā£', user)
await msg_embed.add_reaction('\N{WHITE HEAVY CHECK MARK}')
await msg_embed.add_reaction('\N{CROSS MARK}')
elif (reaction[0].emoji == '2ļøā£'):
user = await client.fetch_user(ctx.author.id)
msg = await user.send("What is your question ?")
question = await client.wait_for("message", check=lambda m: m.author == ctx.author)
msg = await user.send("What are the choices ? (Four compulsory choices, separated by comma)")
choices = await client.wait_for("message", check=lambda m: m.author == ctx.author)
choices = choices.content.split(',')
if (len(choices) > 4):
await msg_embed.delete()
await user.send("You can't have more than four choices")
return
if (len(choices) < 4):
await msg_embed.delete()
await user.send("You can't have less than four choices")
return
answers = ['1ļøā£ '+ choices[0] + '\n', '2ļøā£ '+ choices[1] + '\n', '3ļøā£ '+ choices[2] + '\n', '4ļøā£ '+ choices[3] + '\n']
new_embed = discord.Embed(title=question.content, description="\n ".join(answers), color=0x00ff00)
await msg_embed.edit(embed=new_embed)
await msg_embed.remove_reaction('2ļøā£', user)
await msg_embed.add_reaction('1ļøā£')
await msg_embed.add_reaction('2ļøā£')
await msg_embed.add_reaction('3ļøā£')
await msg_embed.add_reaction('4ļøā£')
Related
I'm trying to create a reactroles function for my server, I've gone through hundreds of stack overflow and reddit forums to find bits and pieces to make this work but nothing has fixed this last error.
The roles are present on my server and properly defined (as far as i know) in the code but still returns error 10011 Unknown Role
async def on_reaction_add(reaction, user):
ChID = '1018712244843970610'
ctx = await bot.get_context(reaction.message)
#user = ctx.reaction.author
Channel = bot.get_channel(1018712244843970610)
if reaction.message.channel != Channel:
await Channel.send("this is a test for ChID not....")
return
if reaction.emoji == "š":
await ctx.channel.purge(limit=1)
this_member = ctx.message.author
mem = str(this_member.display_name)
await Channel.send(mem+" - this is a test for running....š")
print(this_member)
this_guild = this_member.guild
this_role = discord.utils.get(this_guild.roles, id=1018802229341327370)
await this_member.add_roles(this_member, this_role)
if reaction.emoji == "šØ":
await ctx.channel.purge(limit=1)
this_member = ctx.message.author
mem = str(this_member.display_name)
await Channel.send(mem+" - this is a test for hammer....šØ")
this_guild = this_member.guild
this_role = discord.utils.get(this_guild.roles, id=1018802151679602798)
await this_member.add_roles(this_member, this_role)
if reaction.emoji == "š¦":
await ctx.channel.purge(limit=1)
this_member = ctx.message.author
mem = str(this_member.display_name)
await Channel.send(mem+" - this is a test for duck....š¦")
this_guild = this_member.guild
this_role = discord.utils.get(this_guild.roles, id=1018802188555927572)
await this_member.add_roles(this_member, this_role)
if reaction.emoji == "ā¤ļø":
await ctx.channel.purge(limit=1)
this_member = ctx.message.author
mem = str(this_member.display_name)
await Channel.send(mem+" - this is a test for heart....ā¤ļø")
this_guild = this_member.guild
this_role = discord.utils.get(this_guild.roles, id=1018802188555927572)
await this_member.add_roles(this_member, this_role)
I have tried replacing the ctx in ct.message.author with reaction.message.author but then throws the error 'reaction' has no attribute 'content'
I thought maybe the definition of this_member was the cause of it not being able to define the role but it doesnt seem to be the issue
I used this code, and it works:
#bot.event
async def on_raw_reaction_add(payload):
Channel_id = 1018712244843970610
Channel = bot.get_channel(Channel_id)
data = {"š":["running",1018802229341327370], "šØ":["hammer",1018802229341327370], "š¦":["duck",1018802229341327370], "ā¤":["heart",1018802188555927572]}
if payload.channel_id != Channel_id:
await Channel.send("this is a test for ChID not....")
return
if payload.emoji.name in data:
this_guild = await bot.fetch_guild(payload.guild_id)
all_roles = discord.utils.get(this_guild.roles, name="Bot")
text, role_id = data[payload.emoji.name]
await Channel.purge(limit=1)
this_member = await this_guild.fetch_member(payload.user_id)
mem = str(this_member.display_name)
await Channel.send(mem+" - this is a test for {0}....{1}".format(text, payload.emoji))
print(this_member)
this_role = discord.utils.get(this_guild.roles, id=role_id)
await this_member.add_roles(this_member, this_role)
Raw_reaction_add is for messages older than the start of the bot.
If this does not work, check the Ids of the role.
so right now I'm trying to create a type of application bot and right now the check I used for the bot doesn't allow the user to move onto the next question. There is no traceback so it's something with the check I defined.
#commands.command()
#commands.has_role("Realm OP")
async def block(self, ctx, user: discord.User):
DMchannel = await ctx.author.create_dm()
channel = ctx.message.channel
author = ctx.message.author
mentions = [role.mention for role in ctx.message.author.roles if role.mentionable]
channel2 = str(channel.name)
channel = channel2.split('-')
if len(channel2) == 2: # #real-emoji
realm, emoji = channel
else: # #realm-name-emoji
realm, emoji = channel[0], channel[-1]
realmName = realm.replace("-" , " ")
realmName1 = realmName.lower()
rolelist = []
print(realmName1)
a = solve(realmName1)
print(a)
realmName2 = str(a) + " OP"
print(realmName2)
check_role = discord.utils.get(ctx.guild.roles, name= realmName2)
if check_role not in ctx.author.roles:
return await ctx.send('You do not own this channel')
else:
await ctx.send("You own this channel!")
def check(m):
return m.channel == channel and m.author != self.bot.user
await DMchannel.send("Please fill out the questions in order to block the user!")
await DMchannel.send("User's Gamertag: (If you don't know, try using the >search command to see if they have any previous records!) ")
blocka1 = await self.bot.wait_for('message', check=check)
await DMchannel.send("Reason for block:")
blocka2 = await self.bot.wait_for('message', check=check)
Right now the bot doesn't do anything after the user responds to the first question and there is no traceback.
Any help or suggestions would help greatly!
Your check isn't returning anything. It's supposed to return either True or False. This means your wait_for will never end (as the check never returns True), so it will never ask the next question.
def check(m):
return m.channel == channel and m.author != self.bot.user
EDIT:
Your channel is the ctx.channel, while your bot waits for answers in DM. Assuming you answer your bot in DM as well, this means your check will never pass, as m.channel never equals channel.
def check(m):
return m.guild is None and m.author == ctx.author
This checks if a message was sent in DM (Guild is None), and if it was a DM by the original author.
I've tried this and i didn't really get the logic through it, I need some help making it have:
š Emoji
Message
Setting the time
My Code:
#bot.command()
async def giveaway(ctx, msg, duration):
embed=discord.Embed()
embed.title=msg
embed.description="React To Giveaway With š To Join."
embed.set_footer(text="š MTND Bot Development")
embed.color=0x00ffff
msg = await ctx.send(embed=embed)
await msg.add_reaction('š')
Please help if you could.
Here is one.
def convert(time):
pos = ["s","m","h","d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
#client.command()
#commands.has_permissions(kick_members=True)
async def giveaway(ctx):
await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('messsage', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
return
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.send(f"The time just be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
embed.add_field(name = "Hosted by:", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now!")
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("š")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")
#client.command()
#commands.has_permissions(kick_members=True)
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
try:
new_msg = await channel.fetch_message(id_)
except:
await ctx.send("The ID that was entered was incorrect, make sure you have entered the correct giveaway message ID.")
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await channel.send(f"Congratulations the new winner is: {winner.mention} for the giveaway rerolled!")
This is my whole code for my gcreate command
This is a command with embeds and steps
#client.command()
#commands.has_role("Giveaways")
async def gcreate(ctx):
await ctx.send("Let's start with this giveaway!\n`Answer these questions within 15 seconds!`")
questions = ["**Which channel should it be hosted in?**",
"**What should be the duration of the giveaway?** `(s|m|h|d)`",
"**What is the prize of the giveaway?**"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. **Do it like this {ctx.channel.mention} next time.**")
return
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send("You didn't answer the time with a proper unit. Use `(s|m|h|d)` next time!")
return
elif time == -2:
await ctx.send("The time must be a number. Please enter a number next time")
return
elif time < 10:
await ctx.send("Time Cannot Be Less Than 10s!!")
return
prize = answers[2]
await ctx.send(f"The Giveaway will be in {channel.mention} and will last {answers[1]}!")
embed = discord.Embed(title = "Giveaway!", description = "React To š To Enter The **Giveaway**!", color = discord.Color.blue())
embed.add_field(name=":gift: Prize:-", value=f"{prize}", inline=False)
embed.add_field(name=":timer: Ends In:-", value=f"{answers[1]}", inline=False)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(text=f"Hosted By {ctx.author.name}", icon_url=ctx.author.avatar_url)
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("š")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
users.pop(users.index(ctx.author))
if len(users) == 0:
await channel.send("No Winner Was Decided!")
return
winner = random.choice(users)
embed2 = discord.Embed(title = "Giveaway!", description ="**Giveaway Has Ended**!", color = discord.Color.blue())
embed2.add_field(name=":gift: Prize:-", value=f"{prize}", inline=False)
embed2.add_field(name=":trophy: Winner:-", value=f"{winner.mention}", inline=False)
embed2.set_thumbnail(url=ctx.guild.icon_url)
embed2.set_footer(text=f"Hosted By {ctx.author.name}", icon_url=ctx.author.avatar_url)
await my_msg.edit(embed=embed2)
await channel.send(f"Congratulations! {winner.mention} Won The Prize:-`{prize}`!\nhttps://discord.com/channels/{channel.guild.id}/{channel.id}/{my_msg.id}")
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]#client.command()
#commands.has_role("Giveaways")
async def gcreate(ctx):
await ctx.send("Let's start with this giveaway!\n`Answer these questions within 15 seconds!`")
questions = ["**Which channel should it be hosted in?**",
"**What should be the duration of the giveaway?** `(s|m|h|d)`",
"**What is the prize of the giveaway?**"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"You didn't mention a channel properly. **Do it like this {ctx.channel.mention} next time.**")
return
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send("You didn't answer the time with a proper unit. Use `(s|m|h|d)` next time!")
return
elif time == -2:
await ctx.send("The time must be a number. Please enter a number next time")
return
elif time < 10:
await ctx.send("Time Cannot Be Less Than 10s!!")
return
prize = answers[2]
await ctx.send(f"The Giveaway will be in {channel.mention} and will last {answers[1]}!")
embed = discord.Embed(title = "Giveaway!", description = "React To š To Enter The **Giveaway**!", color = discord.Color.blue())
embed.add_field(name=":gift: Prize:-", value=f"{prize}", inline=False)
embed.add_field(name=":timer: Ends In:-", value=f"{answers[1]}", inline=False)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(text=f"Hosted By {ctx.author.name}", icon_url=ctx.author.avatar_url)
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("š")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
users.pop(users.index(ctx.author))
if len(users) == 0:
await channel.send("No Winner Was Decided!")
return
winner = random.choice(users)
embed2 = discord.Embed(title = "Giveaway!", description ="**Giveaway Has Ended**!", color = discord.Color.blue())
embed2.add_field(name=":gift: Prize:-", value=f"{prize}", inline=False)
embed2.add_field(name=":trophy: Winner:-", value=f"{winner.mention}", inline=False)
embed2.set_thumbnail(url=ctx.guild.icon_url)
embed2.set_footer(text=f"Hosted By {ctx.author.name}", icon_url=ctx.author.avatar_url)
await my_msg.edit(embed=embed2)
await channel.send(f"Congratulations! {winner.mention} Won The Prize:-`{prize}`!\nhttps://discord.com/channels/{channel.guild.id}/{channel.id}/{my_msg.id}")
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]**strong text**
```
In order to make an giveaway command you need first of all, on going giveaways variables:
cmdsettings = {}
allowedRiggers = config.riggers
ongoingGiveaways = {}
like that then embed:
actualTitle = 'Giveaway: ' + str(msg)
embed = discord.Embed(color=0x0040ff,title=actualTitle)
info = "React with š on this message to enter"
embed.add_field(name='Message from creator', value=message, inline=False)
embed.add_field(name='How to enter', value=info, inline=False)
embed.add_field(name='Giveaway end date', value=endDate, inline=False)
that end date can be anything, but I am not going to show how to do it since i assume you know python. and them use those vars what i sent before, also this code is based on https://github.com/AnimeHasFallen/discordbot-giveaway/ so view the full source code there.
key39
I'm using discord.py to create a multipurpose discord bot, but I have been having some trouble making custom currency.
I decided on using a .json file to store the names and currency of everyone on the server, but I'm getting this error when I run this:
from dotenv import load_dotenv
from discord.ext import commands
import random
from discord import Game
import discord
import json
load_dotenv()
TOKEN = 'TOKENHERE'
GUILD = os.getenv('DISCORD_GUILD') # Same thing but gets the server name
bot = commands.Bot(command_prefix='r!')
on = "I'm up and running!"
print("Booting up...")
cmds = ["r!test - responds with: I hear you!"]
channel2 = bot.get_channel(CHANNELID)
#bot.event # idk what this means but you have to do it
async def on_ready(): # when the bot is ready
for guild in bot.guilds:
if guild.name == GUILD:
break
print(
f'{bot.user} has connected to Discord! They have connected to the following server: ' # client.user is just the bot name
f'{guild.name}(id: {guild.id})') # guild.name is just the server name
channel2 = bot.get_channel(703869904264101969)
global amounts
try:
with open('amounts.json') as f:
amounts = json.load(f)
except FileNotFoundError:
print("Could not load amounts.json")
amounts = {}
await channel2.send(on)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="r!help"))
#bot.command(name='test', help='Responds with: I can hear you! Used mainly for testing. ')
async def test(ctx):
await ctx.send("I hear you!")
#bot.command(name='ping', help='Tells you the latency of the bot.')
async def ping(ctx):
await ctx.send("Pong! " + str(int(bot.latency) * 1000) + "ms!")
#bot.command(name='say or simonsays', help='Responds with whatever you say after.', aliases = ['say', 'simonsays'])
async def say(ctx, *, contents: str):
await ctx.send(contents)
#bot.command(name='diceroll', help='Rolls a dice!')
async def diceroll(ctx, number_of_dice: int, number_of_sides: int):
dice = [
str(random.choice(range(1, number_of_sides + 1)))
for i in range(number_of_dice)
]
await ctx.send(', '.join(dice))
#bot.event
async def on_member_join(member):
await channel2.send(f'{member} has joined the server.')
#bot.event
async def on_member_remove(member):
await channel2.send(f'{member} has left the server. F')
#bot.command(name='coolnotcool', help='Tells you whether you are cool or not.')
async def coolnotcool(ctx, *, member: str):
coolornot = random.choice(range(1, 3))
if coolornot == 1:
await ctx.send(f'{member} is cool.')
elif coolornot == 2:
await ctx.send(f'{member} is not cool.')
#bot.command(name='8ball', help='Ask it a question and it will respond')
async def eightball(ctx, question):
answers=['It is certain.', 'Without a doubt.', 'You may rely on it.', 'Yes, definitely.', 'It is decidedly so.', 'As I see it, yes.', 'Most likely.', 'Yes.', 'Outlook good.', 'Signs point to yes.', 'Reply hazy, try again.', 'Better not tell you now.', 'Ask again later.', 'Cannot predict now.', 'Concentrate, then ask again.', 'Dont count on it.', 'Outlook not so good.', 'My sources say no.', 'Very doubtful.', 'My reply is no.']
response = random.choice(range(1, 21))
await ctx.send(str(answers[response]))
#bot.command(name='coinflip', help='Responds with either heads or tails. Good for making a decision.')
async def coinflip(ctx):
answer = random.choice(range(1, 3))
if answer == 1:
await ctx.send('Heads!')
else:
await ctx.send('Tails!')
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please pass in all required arguments.')
bot.run(TOKEN)
#bot.command(pass_context=True, name='bal', help='Shows you how many rb you have in the bank.')
async def bal(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} in the rb bank".format(amounts[id]))
else:
await ctx.send("You do not have an account yet. Type r!register to register!")
#bot.command(pass_context=True, name='register', help='Register to start using RuinBot currency!')
async def register(ctx):
id = str(ctx.message.author.id)
if id not in amounts:
amounts[id] = 100
await ctx.send("You are now registered! Remember, type r!save to save!")
_save()
else:
await ctx.send("You already have an account.")
#bot.command(name='save', help='Your currency autosaves, but remember to always save just in case! This saves your currency.')
async def save(ctx):
_save()
await ctx.send("Data saved!")
#bot.command(pass_context=True, name='give', help='Give another member some rb!')
async def give(ctx, amount: int, other: discord.Member):
primary_id = str(ctx.message.author.id)
other_id = str(other.id)
if primary_id not in amounts:
await ctx.send("You do not have an account")
elif other_id not in amounts:
await ctx.send("The other party does not have an account")
elif amounts[primary_id] < amount:
await ctx.send("You cannot afford this transaction")
else:
amounts[primary_id] -= amount
amounts[other_id] += amount
await ctx.send("Transaction complete")
_save()
def _save():
with open('amounts.json', 'w+') as f:
json.dump(amounts, f)
If anyone could help with this, that would be great. The .json file is empty.
The empty json file is your error. Edit the json file so that it contains the following:
{}
I'm looking to make a command where if the message.author tags a user, the bot will react twice to the message then will wait for the user who was tagged to select either one or the other reaction to choose. Right now everything works except when the user reacts to one or the other emoji, it doesn't do anything. When they react to both emojis, it sends the message for reaction.
if message.content.lower().startswith('!marry'):
user = message.mentions[0]
if message.author == user:
await client.send_message(message.channel, "{} you can't marry yourself dummy š".format(message.author.mention))
else:
if get_spouse(message.author) != "No One":
await client.send_message(message.channel, "{}, you're already married to {} š".format(message.author.mention, get_spouse(message.author)))
else:
if (get_spouse(user)) != "No One":
await client.send_message(message.channel, "{} is already married. Get your own spouse. š".format(user.mention))
else:
marriagemsg = await client.send_message(message.channel, "{} *has proposed to* {} š".format(message.author.mention, user.mention))
await client.add_reaction(marriagemsg, "ā
")
await client.add_reaction(marriagemsg, "ā")
while True:
reaction = await client.wait_for_reaction(emoji="ā
", message=marriagemsg,
check=lambda reaction, user: user == message.mentions[0])
reaction2 = await client.wait_for_reaction(emoji="ā", message=marriagemsg,
check=lambda reaction, user: user == message.mentions[0])
if reaction:
await client.send_message(message.channel, "{} **is now married to** {} š¤µš°".format(message.author.mention, reaction.user.mention))
add_spouse(message.author, user.name)
add_spouse(reaction.user, message.author.name)
else:
if reaction2:
await client.send_message(message.channel, "{} **rejects** {}**'s proposal** āš".format(reaction2.user.mention, message.author.mention))
The multiple wait_for_reaction checks that you are using is causing this. The bot will wait until the user reacts with ā
on marriagemsg and only then check if the user reacts with ā.
Instead of using multiple wait_for_reaction checks, just use one and populate your emojis in a list. You can also use elif instead of else: if.
if message.content.lower().startswith('!marry'):
user = message.mentions[0]
if message.author == user:
await client.send_message(message.channel, "{} you can't marry yourself dummy š".format(message.author.mention))
else:
if get_spouse(message.author) != "No One":
await client.send_message(message.channel, "{}, you're already married to {} š".format(message.author.mention, get_spouse(message.author)))
else:
if (get_spouse(user)) != "No One":
await client.send_message(message.channel, "{} is already married. Get your own spouse. š".format(user.mention))
else:
marriagemsg = await client.send_message(message.channel, "{} *has proposed to* {} š".format(message.author.mention, user.mention))
await client.add_reaction(marriagemsg, "ā
")
await client.add_reaction(marriagemsg, "ā")
answer = await client.wait_for_reaction(emoji=["ā
", "ā"], message=marriagemsg,
check=lambda reaction, user: user == message.mentions[0])
if answer.reaction.emoji == "ā
":
await client.send_message(message.channel, "{} **is now married to** {} š¤µš°".format(message.author.mention, answer.user.mention))
add_spouse(message.author, user.name)
add_spouse(answer.user, message.author.name)
elif answer.reaction.emoji == "ā":
await client.send_message(message.channel, "{} **rejects** {}**'s proposal** āš".format(answer.user.mention, message.author.mention))