Discord API cloudflare banning my repl.it repo - python

#type: ignore
import os
from keep_alive import keep_alive
from discord.ext import commands
import discord
import asyncio
import datetime
import re
DC_TOK = os.environ['DC_TOK']
bot = commands.Bot(command_prefix='!', intents=discord.Intents(4194303))
#bot.event
async def on_message(msg: discord.Message):
if msg.author == bot.user:
return
guild = msg.guild
if msg.content == '!quack':
await msg.channel.send('''!ticket open subject - Creates a new ticket
**Ticket Support Team++**
!ticket close - Closes on-going ticket
!invite ping_message - Invites user to ticket
!remove ping_message - Removes user from ticket
!mark rank - Makes the ticket exclusive for specific rank
!category TITLE - Briefly categorises the ticket
''')
elif msg.content[:12] == '!ticket open':
chn = msg.channel
ticket_title = msg.content[13:]
if ticket_title.strip() == '':
ticket_title = 'None'
ticketer_acc = msg.author
ticketer = ticketer_acc.display_name
category = discord.utils.get(guild.categories, name="Tickets 2")
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
elem = None
_ = None
async for mg in tcc.history():
if mg.content.startswith('CATEG'):
continue
elem, _ = mg.content.split(' ')
elem = int(elem)
_ = int(_)
break
assert (elem is not None)
elem += 1
await tcc.send(str(elem) + ' ' + str(msg.author.id))
tck_channel = await guild.create_text_channel(f'{elem}-{ticketer}',
category=category)
await tck_channel.set_permissions(ticketer_acc,
read_messages=True,
send_messages=True)
await chn.send(
f'**TICKET {elem}**\n\nYour ticket has been created. <#{tck_channel.id}>'
)
await tck_channel.send(
f'<#{ticketer_acc.id}> Hello emo! Your ticket has been created, subject: `{ticket_title}`.\nOur support team will be with you soon! Meanwhile please address your problem because those emos are really busy!!!'
)
elif msg.content == '!ticket close':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
closed_cat = discord.utils.get(guild.categories, name="Tickets 3")
nam = msg.channel.name.lstrip('๐Ÿ”ฑ๐Ÿ›ก๏ธ')
tick_id = int(nam[:nam.find('-')])
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
elem = None
creator = None
async for mg in tcc.history():
if mg.content.startswith('CATEG'):
continue
elem, creator = mg.content.split(' ')
elem = int(elem)
creator = int(creator)
if elem == tick_id:
break
assert (elem is not None)
await msg.channel.send('Closing ticket...')
counter = {}
async for mg in msg.channel.history():
if mg.author.bot or mg.author.id == creator:
continue
if mg.author.id not in counter.keys():
counter[mg.author.id] = 1
else:
counter[mg.author.id] += 1
max_num = 0
max_authors = []
for key, value in counter.items():
if value > max_num:
max_num = value
max_authors = [key]
elif value == max_num:
max_authors.append(key)
user_ping_list = ' '.join([f'<#{usr}>' for usr in max_authors
]) + ' contributed the most.'
if user_ping_list == ' contributed the most.':
user_ping_list = 'No one contributed.'
await msg.channel.send(user_ping_list)
await msg.channel.send('We hope we were able to solve your problem.')
await asyncio.sleep(3)
tick_creator = discord.utils.get(guild.members, id=creator)
assert (tick_creator is not None)
await msg.channel.set_permissions(tick_creator, overwrite=None)
await msg.channel.edit(category=closed_cat)
dms = discord.utils.get(guild.members, id=creator)
assert (dms is not None)
DM = dms
dms = DM._user.dm_channel
if dms is None:
dms = await DM._user.create_dm()
del DM
cr = msg.channel.created_at
assert (cr is not None)
tick_created: datetime.datetime = cr.replace(tzinfo=None)
time_cur = datetime.datetime.utcnow().replace(tzinfo=None)
td = time_cur - tick_created
mm, ss = divmod(td.seconds, 60)
hh, mm = divmod(mm, 60)
timestr = ''
if td.days > 0:
timestr += f'{td.days}d '
if hh > 0:
timestr += f'{hh}h '
if mm > 0:
timestr += f'{mm}m '
if ss > 0:
timestr += f'{ss}s'
await dms.send(f'''Your ticket has been closed by <#{msg.author.id}>
Your ticket lasted `{timestr}`.
We hope we were able to solve your problem. :partying_face:''')
elif msg.content == '!mark co':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
await msg.channel.send('Requesting to mark this ticket for: `Co-owner`')
nam = msg.channel.name
if nam.startswith('๐Ÿ›ก๏ธ'):
nam = nam[1:]
assert (nam is not None)
if nam.startswith('๐Ÿ”ฑ'):
await msg.channel.send('Ticket already marked for `Co-owner`')
else:
await msg.channel.edit(name='๐Ÿ”ฑ' + nam)
await msg.channel.send(
f'<#{msg.author.id}> marked this ticket for: `Co-owner`')
await msg.channel.send(':trident:')
elif msg.content == '!mark admin':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
await msg.channel.send(
'Requesting to mark this ticket for: `Administrator`')
nam = msg.channel.name
assert (nam is not None)
if nam.startswith('๐Ÿ›ก๏ธ'):
await msg.channel.send('Ticket already marked for `Administrator`')
elif nam.startswith('๐Ÿ”ฑ'):
await msg.channel.send('Ticket already marked for `Co-owner`')
else:
await msg.channel.edit(name='๐Ÿ›ก๏ธ' + nam)
await msg.channel.send(
f'<#{msg.author.id}> marked this ticket for: `Adiministrator`')
await msg.channel.send(':shield:')
elif msg.content[:7] == '!invite':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
usr_ping = msg.content[8:]
if not (usr_ping.startswith('<#') and usr_ping.endswith('>')
and usr_ping[2:-1].isdigit()):
return
invited_usr = discord.utils.get(guild.members, id=int(usr_ping[2:-1]))
assert (invited_usr is not None)
await msg.channel.set_permissions(invited_usr,
read_messages=True,
send_messages=True)
await msg.channel.send(f'{usr_ping} was invited into the ticket.')
elif msg.content[:7] == '!remove':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
usr_ping = msg.content[8:]
if not (usr_ping.startswith('<#') and usr_ping.endswith('>')
and usr_ping[2:-1].isdigit()):
return
invited_usr = discord.utils.get(guild.members, id=int(usr_ping[2:-1]))
assert (invited_usr is not None)
await msg.channel.set_permissions(invited_usr, overwrite=None)
await msg.channel.send(f'{usr_ping} was removed from the ticket.')
elif msg.content[:9] == '!category':
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
if not (discord.utils.get(guild.roles, name='Ticket support team')
in msg.author.roles or discord.utils.get(
guild.roles, name='Administrator') in msg.author.roles
or discord.utils.get(guild.roles,
name='Co-owners (A.K.A. super admin)')
in msg.author.roles or discord.utils.get(
guild.roles, name='Owner') in msg.author.roles):
return
categ = msg.content[10:]
tcc = discord.utils.get(guild.channels, name="ticket-creation-logs")
nam = msg.channel.name.lstrip('๐Ÿ”ฑ๐Ÿ›ก๏ธ')
tick_id = int(nam[:nam.find('-')])
async for mg in tcc.history():
if mg.content.startswith(f'CATEG {tick_id}'):
await msg.channel.send(
f'''This ticket is already marked with category **{mg.content[len(f'CATEG{tick_id}')+2:]}**'''
)
return
await tcc.send(f'CATEG {tick_id} {categ}')
await msg.channel.send(
f'''<#{msg.author.id}> marked this ticket with category **{categ}**''')
else:
category = discord.utils.get(guild.categories, name="Tickets 2")
if msg.channel.category != category:
return
PING_PTN = '<#[0-9]+>'
pings = re.findall(PING_PTN, msg.content, re.UNICODE)
usrs = [
discord.utils.get(guild.members, id=int(ping[2:-1])) for ping in pings
]
remainder = msg.content
for ping in pings:
remainder = remainder.replace(str(ping), '')
for usr in usrs:
assert (usr is not None)
DM = usr
dms = DM._user.dm_channel
if dms is None:
dms = await DM._user.create_dm()
del DM
await dms.send(
f'''`{msg.author.name}#{msg.author.discriminator}`Pinged you in a ticket: <#{msg.channel.id}>
`{remainder}`''')
keep_alive()
bot.run(DC_TOK)
main.py
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
keep_alive.py
I am hosting my project on repl.it and using uptimerobot to ping it every 10 minutes so that it does not go dormant. But discord cloudflare bans it. I hear some say it's because of uptimerobot but how does that even affect the discord API? Also, the plan you give me must not require payment or payment methods of any type. I am a minor.

As moinierer3000 said,
Replit uses shared IPs to host your Discord bots.
This means that when you run your bots, it sends requests to Discord servers, that are proxies by Cloudflare that rate-limits how much requests an IP can make to defend the app from DDoS attacks.
I'd recommend you to just shutdown the bot, wait 15-30 minutes and try again later. I've done this numerous times and it worked great.
Hope this answer helped you.

This question has been solved
SOLUTION: find another cloud server because it is rate limited.

Related

Send winnings from a specific account using python and json in python

`Hi Guys,
I need some help.
So.. ive been developing a discord bot over the last year and trying to make some improvements to the games i have made.. it is basically an economy system that allows users to transfer funds to one another, place bets, and recieve winnings etc.
I have created a slots game that automatically generates winnings and economy but my idea is to modify an exisiting heads or tails game with the same functions to basically:
Allow a user to deposit a bet into an account that holds the winnings/profits/bets etc.
The user will then either select heads or tails to win the challenge.
The winnings will then be transferred directly from the specific account.
My current code is:
mport discord
import random
from discord.ext import commands
from discord.ext import commands, tasks
from discord.ui import select, View
from discord.embeds import Embed
from discord import colour
import asyncio
from itertools import cycle
import os
import json
import datetime
from random import choice
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents) #Command prefix
#Notifies vs code that the bot is running on VS code#
#client.event
async def on_ready():
print("Bot is ready")
#Slot machine command when user enters !slots 50#
#client.command(pass_context=True)
async def slots(ctx, amount=None):
if amount == None:
em = discord.Embed(title=f'โ“Please enter an amountโ“',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount > bal[0]:
em = discord.Embed(title=f'โŒYou do not have sufficient balanceโŒ')
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
if amount < 0:
em = discord.Embed(title=f'โ—Amount must be positiveโ—')
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
slots = ['๐Ÿงโ€โ™‚๏ธ', '๐Ÿ”ฅ']
slot1 = slots[random.randint(0, 1)]
slotOutput = '| :{}: |\n'.format(slot1)
ok = discord.Embed(title = "RTC slot machine", color = discord.Color(0xFFEC))
ok.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {1.9*amount} coins')
won = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
won.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {1.9*amount} coins')
if slot1:
await update_bank(ctx.author, 1.9 * amount)
await ctx.send(embed = won)
return
The deposit bet command for the agreed bet when user enters !db #hostname 500 for example#
#client.command()
async def db(ctx,member : discord.Member,amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
em = discord.Embed(title=f'โ“Please enter an amount you wish to betโ“',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
bal = await update_bank(ctx.author)
if amount == 'all':
amount = bal[0]
amount = int(amount)
if amount > bal[0]:
em = discord.Embed(title=f'โŒYou do not have sufficient balanceโŒ',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
if amount < 0:
em = discord.Embed(title =f'โ—Amount must be positiveโ—',color = discord.Color.red())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
return
await update_bank(ctx.author,-1*amount,'wallet')
await update_bank(member,amount,'bank')
em = discord.Embed(title=f'โš”{ctx.author.name} sent {amount}M RS3 to {member}', description=f'Please select the game/challenge !coinflip !elements or !yesandnoโš”',color = discord.Color.green())
em.timestamp = datetime.datetime.utcnow()
await ctx.send(embed= em)
#Creates account details for member of the channel#
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open('bank.json','w') as f:
json.dump(users,f)
return True
#Stores the user wallet amount in the bank.json file#
async def get_bank_data():
with open('bank.json','r') as f:
users = json.load(f)
return users
#Updates the users bank details held within the json file.
async def update_bank(user,change=0,mode = 'wallet'):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open('bank.json','w') as f:
json.dump(users,f)
bal = users[str(user.id)]['wallet'],users[str(user.id)]['bank']
return bal
client.run("'''''")
Im looking for a way to modify the code so it takes the winnings from a specific account by implimenting the account ID or username.
Any ideas?`

My discord python bot's shop cause it to freeze

I have been making a discord economy bot and it has a shop.
When I try and buy an item from my shop in the bot, the bot does not respond with anything and I won't recognise any other commands. The bot also gives me an error in the command prompt. This error is in the picture. Any help given is great.
https://i.stack.imgur.com/SsBwA.png
My code:
mainshop = [{"name":"Airbus A320","price":400,"description":"test description"}]
#client.command()
async def shop(ctx):
em = discord.Embed(title = "Dealership")
for item in mainshop:
name = item["name"]
price = item["price"]
desc = item["description"]
em.add_field(name = name, value = f"${price} | {desc}")
await ctx.send(embed =em)
#client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That item does not exisit!")
return
if res [1]==2:
await ctx.send(f"You do not have enough money!")
return
await ctx.send(f"you just bought {amount} {item}")
async def buy_this(user,item_name,amount):
item_name - item_name.lower()
name_ = None
for item in mainshop:
name = item["name"].lower()
if name == item_name:
name_ = name_
price = item["price"]
break
if name_ ==None:
return [False,1]
cost = price*amount
users = await get_bank_data()
bal = await update_bank(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"] =[obj]
with open("bank.json","w") as f:
json.dump(users,f)
await update_bank(user,cost*-1,"Wallet")
return [True,"Worked"]```
you have a typing mistake in buy_this function.
item_name - item_name.lower()
You need to put '=' instead of '-', like this:
item_name = item_name.lower()

Making embeds of more than one page using discord.py

I'm currently trying to make a bot using discord.py. One of the functions I want it to have is to show the users with X role. I've managed to create said function, and make the bot send the results with a nice embed. However, now I want to improve it and make it more similar to Nadeko's inrole function (i.e. only one embed and the user can react to it to change the page).
#client.command(name = "inrole", brief = "Users with a certain role",
description= "I'll give you a list with all the users with a certain role.", pass_context=True)
async def inrole(ctx, *args):
server = ctx.message.guild
role_name = (' '.join(args))
role_id = server.roles[0]
for role in server.roles:
if role_name.lower() == role.name.lower():
role_id = role
break
else:
await ctx.send(f"Oh noes! That role doesn't exist!")
return
n = 0
members = []
for member in server.members:
if role_id in member.roles:
n += 1
name = str(n) + ". " + member.name + " #" + member.discriminator + "\n"
members.append(name)
composite_members = [members[x:x + 20] for x in range(0, len(members), 20)]
for elements in composite_members:
string = ""
for element in elements:
string = string + element
embedVar = discord.Embed(title=f"List of users with {role} - {n}", colour=discord.Colour.blue())
embedVar.add_field(name = "Members", value = string)
await ctx.send(embed=embedVar)
I've read the documentation, but I'm still quite lost in how to make it like Nadeko's. Right now, if there are 200 users with that role, then it will print 10 embeds, which can be rather annoying.
Thanks in advance!
EDIT:
I've improved the code a bit, but now I have a different problem.
def predicate(message, l, r):
def check(reaction, user):
if reaction.message.id != message.id or user == client.user:
return False
if l and reaction.emoji == "โช":
return True
if r and reaction.emoji == "โฉ":
return True
return False
return check
#inrole function. To see all members with that role
#client.command(name = "inrole", brief = "Users with a certain role",
description= "I'll give you a list with all the users with a certain role.", pass_context=True)
async def inrole(ctx, *role):
server = ctx.message.guild
role_name = (' '.join(role))
role_id = server.roles[0]
for role in server.roles:
if role_name.lower() == role.name.lower():
role_id = role
break
else:
await ctx.send(f"Oh noes! That role doesn't exist!")
return
n = 0
members = []
for member in server.members:
if role_id in member.roles:
n += 1
name = str(n) + ". " + member.name + " #" + member.discriminator + "\n"
members.append(name)
composite_members = [members[x:x + 20] for x in range(0, len(members), 20)]
pages = []
for elements in composite_members:
string = ""
for element in elements:
string = string + element
embedVar = discord.Embed(title=f"List of users with {role} - {n}", colour=discord.Colour.blue())
embedVar.add_field(name = "Members", value = string)
pages.append(embedVar)
page = 0
left = "โช"
right = "โฉ"
while True:
msg = await ctx.send(embed = pages[(page)])
l = page != 0
r = page != len(pages) - 1
if l:
await msg.add_reaction(left)
if r:
await msg.add_reaction(right)
# bot.wait_for_reaction
react = await client.wait_for('reaction_add', check=predicate(msg, l, r))
if react[0] == left:
page -= 1
elif react[0] == right:
page += 1
await msg.delete()
In the last if/elif statement, it doesn't work. There isn't an error, but although react[0] is the same emoji as right or left (respectively), page never changes, and thus the embed doesn't change either. I changed the elif for an else, and it that case it does work, but it can only go forward.
Figured it out. Issue was that react[0] wasn't the same type as left and right. Here's the solution for that issue, if anyone is interested:
if str(react[0]) == left:
page -= 1
elif str(react[0]) == right:
page += 1
The rest of the code is exactly the same as the one I posted in the edit.
message_ = None
#client.command()
async def edit(ctx):
global message_
message_ = await ctx.send('EMBED PAGE[1]')
#client.event
async def on_reaction_add(reaction, user):
global message_
msg_ID = 487165969903517696
if int(reaction.message.id) != ChID:
return;
elif user.reaction.emoji == "๐Ÿƒ":
message_.edit(content='EMBED PAGE [2]')
this is just an idea! I'm not sure this code works but there is an option to edit our embed message! so use that to make your embed message better [documentation for edit]

Poll command discord.py

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๏ธโƒฃ')

Random.Randint() Repeating

I have this game where you need to react with the 5 random emojis sent from a list. The problem is that sometimes random.randint() spits out the same emoji twice so its impossible react twice to the same message with the same emoji. Is there a better way of doing multiple random.randints?
async def food_loop():
await client.wait_until_ready()
channel = client.get_channel("523262029440483329")
while not client.is_closed:
foodtime = random.randint(1440, 1880)
food = ['๐Ÿ‡','๐Ÿˆ','๐Ÿ‰','๐ŸŠ','๐Ÿ‹','๐ŸŒ','๐Ÿ','๐ŸŽ','๐Ÿ','๐Ÿ','๐Ÿ‘','๐Ÿ’','๐Ÿ“','๐Ÿฅ','๐Ÿ…','๐Ÿฅ‘','๐Ÿ†','๐Ÿฅ”','๐Ÿฅ•','๐ŸŒฝ','๐ŸŒถ',
'๐Ÿฅ’','๐Ÿ„','๐Ÿฅœ','๐ŸŒฐ','๐Ÿž','๐Ÿฅ','๐Ÿฅ–','๐Ÿฅž','๐Ÿง€','๐Ÿ–','๐Ÿ—','๐Ÿฅ“','๐Ÿ”','๐ŸŸ','๐Ÿ•','๐ŸŒญ','๐ŸŒฎ','๐ŸŒฏ',
'๐Ÿฅ™','๐Ÿณ','๐Ÿฅ˜','๐Ÿฒ','๐Ÿฅ—','๐Ÿฟ','๐Ÿฑ','๐Ÿ˜','๐Ÿ™','๐Ÿš','๐Ÿ›','๐Ÿœ','๐Ÿ','๐Ÿ ','๐Ÿข','๐Ÿฃ','๐Ÿค','๐Ÿฅ','๐Ÿก',
'๐Ÿฆ','๐Ÿง','๐Ÿจ','๐Ÿฉ','๐Ÿช','๐ŸŽ‚','๐Ÿฐ','๐Ÿซ','๐Ÿฌ','๐Ÿญ','๐Ÿฎ','๐Ÿฅ›','โ˜•','๐Ÿต','๐Ÿถ','๐Ÿพ','๐Ÿท','๐Ÿธ','๐Ÿน','๐Ÿบ',
'๐Ÿฅƒ']
food1 = food[random.randint(0,79)]
food2 = food[random.randint(0,79)]
food3 = food[random.randint(0,79)]
food4 = food[random.randint(0,79)]
food5 = food[random.randint(0,79)]
foodmonies = random.randint(350,750)
up = 'order up'
def orderup(m):
return m.content.lower() == up
foodmsg = 'Customer has ordered {}, {}, {}, {}, and {}! Fulfill their order ASAP!'.format(food1, food2, food3, food4, food5)
foodmsgsend = await client.send_message(channel, foodmsg)
foodpay1 = await client.wait_for_reaction(emoji=food1, message=foodmsgsend, timeout=3600,
check=lambda reaction, user: user != client.user)
foodpay2 = await client.wait_for_reaction(emoji=food2, message=foodmsgsend, timeout=3600,
check=lambda reaction, user: user != client.user)
foodpay3 = await client.wait_for_reaction(emoji=food3, message=foodmsgsend, timeout=3600,
check=lambda reaction, user: user != client.user)
foodpay4 = await client.wait_for_reaction(emoji=food4, message=foodmsgsend, timeout=3600,
check=lambda reaction, user: user != client.user)
foodpay5 = await client.wait_for_reaction(emoji=food5, message=foodmsgsend, timeout=3600,
check=lambda reaction, user: user != client.user)
foodguess = await client.wait_for_message(timeout=3600, channel=channel, check=orderup)
if foodpay1 and foodpay2 and foodpay3 and foodpay4 and foodpay5 and foodpay3.user.id in blacklist:
pass
else:
if foodpay1 and foodpay2 and foodpay3 and foodpay4 and foodpay5 and foodguess:
await client.delete_message(foodmsgsend)
await client.send_message(channel, "{} fulfills the order and earns ${}".format(foodpay5.user.mention, foodmonies))
add_dollars(foodpay5.user, foodmonies)
await asyncio.sleep(int(foodtime))
Random numbers can, by definition, be repetitive as any call to randint is independent of the previous one. You can replace the following:
food1 = food[random.randint(0,79)]
food2 = food[random.randint(0,79)]
food3 = food[random.randint(0,79)]
food4 = food[random.randint(0,79)]
food5 = food[random.randint(0,79)]
with this:
food1, food2, food3, food4, food5 = random.sample(food, 5)
From the docs (emphasis mine):
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence or set.
That being said, it is a better idea to refactor that part and switch to using a list instead of declaring 5 variables (it would've been messier if you needed 50, or 500).

Categories