async def main(client, message, params): error = NoticeEmbed(title="Sub") success = SuccessEmbed(title="Sub") try: if len(str(message.content).split(' ')) == 2: sub = str(message.content).split(' ')[1] if sub.lower() in ['yes', 'no', 'ja', 'nein', 'true', 'false']: if ['yes', 'no', 'ja', 'nein', 'true', 'false'].index( sub.lower()) % 2 == 0: # resubs subs(True, message.author.id) success.description = "Done." await message.channel.send(embed=success) else: # unsubs subs(False, message.author.id) success.description = f"Done.\nYou can resubscribe by typing {cfg.options['invoke_normal']}sub True" await message.channel.send(embed=success) else: error.description = f"Invalid syntax.\nPlease use {cfg.options['invoke_normal']}sub True|False" await message.channel.send(embed=error) else: error.description = f"Invalid syntax.\nPlease use {cfg.options['invoke_normal']}sub True|False" await message.channel.send(embed=error) except: error = ErrorEmbed(title="Sub") SHL.output(f"Something went wrong while handling a sub.") error.description = "Something went wrong. Please contact an admin." await message.channel.send(embed=error)
async def end_poll(args): client = args[0] data = handleJson.read_json_raw(path) if data["arena_status"] == "poll": SHL.output("Ended poll") channel = client.get_channel(cfg.options["channel_ids"]["arena"]) results = [0] * data["participant_count"] emojis = ['1⃣', '2⃣', '3⃣', '4⃣'] msg = await channel.fetch_message(data["last_poll_msg"]) reactions = msg.reactions for reaction in reactions: if str(reaction) in emojis: results[emojis.index(str(reaction))] = reaction.count max_votes = max(results) embed = SuccessEmbed(title="Arena") embed.description = f"{data['participants_name'][results.index(max_votes)]} won." if results.count(max_votes) > 1: all_max = [e for e, i in enumerate(results) if i == max_votes] embed.description = ", ".join([data["participants_name"][x] for x in all_max]) + \ f" won with {max_votes} votes." # TODO: reputation system? await channel.send(embed=embed) info = InfoEmbed(title="Arena - Results", description=f'We got a winner! Be sure to check <#{cfg.options["channel_ids"]["arena"]}>') for m in data["participants"]: try: member = channel.guild.get_member(m) await member.send(embed=info) except: pass data["arena_status"] = "wait_topic" handleJson.saveasjson(path, data)
async def main(client, message, params): if any([ x in message.content.lower() for x in ["help", "info", "details", "about"] ]): await message.channel.send(embed=about_embed) return if "true" in message.content.lower(): with open(os.path.join(content_dir, "unsubs.json"), "r") as fh: data = json.load(fh) try: data["unsub_ids"].remove(message.author.id) except ValueError: pass with open(os.path.join(content_dir, "unsubs.json"), "w") as fh: json.dump(data, fh) await message.channel.send(embed=SuccessEmbed( title="Analyzer", description="Deine Nachrichten werden nun wieder erfasst.")) return if "false" in message.content.lower(): with open(os.path.join(content_dir, "unsubs.json"), "r") as fh: data = json.load(fh) if message.author.id not in data["unsub_ids"]: data["unsub_ids"].append(message.author.id) with open(os.path.join(content_dir, "unsubs.json"), "w") as fh: json.dump(data, fh) await message.channel.send(embed=SuccessEmbed( title="Analyzer", description="Deine Nachrichten werden nun nicht erfasst.\n" "Um diesen Vorgang rückgängig zu machen verwende `_analyze true`.") ) return
async def main(client, message, params): error = NoticeEmbed(title="Respond") success = SuccessEmbed(title="Respond") if len(str(message.content).split(' ')) >= 3: submit_id = str(message.content).split(' ')[1][1:] if submit_id.isdigit(): data = handleJson.read_json_raw(path) if submit_id in data.keys(): if data[submit_id]["answer"] == "": embed = create_embed(submit_id, message.author.name, params) msg = await message.channel.send(embed=embed) await msg.add_reaction('✅') await msg.add_reaction('❌') def check(reaction, user): e = str(reaction.emoji) return user == message.author and e.startswith( ('✅', '❌')) reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) if str(reaction.emoji).startswith('❌'): return author_id = data[submit_id]["authorID"] submit_author = get( client.get_guild(531445761733296130).members, id=int(author_id)) try: await submit_author.send(embed=embed) success.description = "Antwort abgeschickt!" await message.channel.send(embed=success) except: # user does not allow dm error = ErrorEmbed( title="Respond", description="User does not allow direct messages.") message.channel.send(embed=error) data[submit_id]["answer"] = ' '.join( str(message.content).split(' ')[2:]) data[submit_id]["answerfrom"] = str(message.author) handleJson.saveasjson(path, data) else: error.description = f"#{submit_id} wurde schon beantwortet:" error.add_field(name=data[submit_id]["answerfrom"], value=data[submit_id]["answer"]) await message.channel.send(embed=error) else: error.description = f"#{submit_id} could not be assigned to a submit." await message.channel.send(embed=error) else: error.description = f"{submit_id} is an invalid ID." await message.channel.send(embed=error) else: error.description = f"Invalid syntax.\nPlease use {cfg.options['invoke_mod']}respond #id text" await message.channel.send(embed=error)
async def main(client, message, params): return # not implemented right now data = handleJson.read_json_raw(path) success = SuccessEmbed(title="Queue") if message.author.id in data["queue"]: data["queue"].remove(message.author.id) success.description = "Removed you from queue" else: data["queue"].append(message.author.id) success.description = f"Added to queue. There are {len(data['queue'])} members in queue." await message.channel.send(embed=success) handleJson.saveasjson(path, data)
async def main(client, message, params): try: last_id = save_json(message) except: SHL.output(f"Something went wrong while handling a submit.") error = WarningEmbed( title="Submit", description="Something went wrong. Please contact an admin.") await message.channel.send(embed=error) return if not cfg.options["channel_ids"].get("suggestions", 0): error = WarningEmbed( title="Submit", description= "Your submit got saved. But could not be send.\nPlease contact an admin." ) await message.channel.send(embed=error) else: embed = InfoEmbed(title=f"Submit #{last_id}", description=' '.join(params)) channel = get(client.get_all_channels(), id=cfg.options["channel_ids"]["submits"]) await channel.send(embed=embed) return_embed = SuccessEmbed( title=f"Submit #{last_id}", description="Thank your for your submission.\n" "If a team member answers it, I will forward the message :)") await message.channel.send(embed=return_embed)
async def close_channel(args): client = args[0] data = handleJson.read_json_raw(path) data["arena_status"] = 0 channel = client.get_channel(cfg.options["channel_ids"]["1v1"]) role = get(channel.guild.roles, id=cfg.options["1v1_role"]) for e, m in enumerate(data["participants"]): data["participants"][e] = channel.guild.get_member(m) info = SuccessEmbed(title="Challenge - Closed", description="Channel closed. Thank you for your discussion.\n") for m in data["participants"]: try: await m.remove_roles(role) await m.send(embed=info) except: pass info.description += "Who won?:\n" \ f"1⃣ {data['participants'][0].mention}\n" \ f"2⃣ {data['participants'][1].mention}\n" msg = await channel.send(embed=info) for e in ['1⃣', '2⃣']: await msg.add_reaction(e) await channel.edit(topic="") SHL.output("Closed discussion") clear_tag("challenge") data["participants"] = [] handleJson.saveasjson(path, data)
async def main(client, message, params): to_warn = message.mentions if not to_warn: except_embed = WarningEmbed(title="No users supplied", description=f"Usage: {cfg.options.get('invoke_normal')}warn @user") await message.channel.send(embed=except_embed) for user in to_warn: warned = get(message.guild.roles, id=cfg.options.get("warn_role_id", 0)) in user.roles if not warned: try: warn_role = get(message.guild.roles, id=cfg.options.get("warn_role_id", 0)) await user.add_roles(warn_role) except HTTPException: if cfg.options.get("warn_role_id", 0): except_embed = WarningEmbed(title="Role-assigment failed", description=f"Failed to assign role {cfg.options.get('warn_role_id', 0)}!") else: except_embed = WarningEmbed(title="Role-assigment failed", description=f"No 'warn_role_id' defined!") await message.channel.send(embed=except_embed) return return_embed = SuccessEmbed(title="Warn", description=f"Warned {user.display_name}") try: pm_embed = InfoEmbed(title="Warn", description=f"You were warned by {message.author.display_name}\n" f"Please read our server rules.\n" f"If you do not understand this message, please ask a moderator.") await user.send(embed=pm_embed) except HTTPException: # if users privacy settings do not allow dm pass await message.channel.send(embed=return_embed) else: warned_embed = NoticeEmbed(title="Warn", description=f"User {user.display_name} has already been warned once!") await message.channel.send(embed=warned_embed)
async def main(client, message, params): success = SuccessEmbed(title="Answer") error = NoticeEmbed(title="Answer") try: data = handleJson.read_json_raw(path_to_surveys) unsubs = handleJson.read_json_raw(path_to_unsubs) except: error = ErrorEmbed( title="Submit", description="Something went wrong. Please contact an admin.") await message.channel.send(embed=error) return embed = error try: if not subscribed(unsubs, message.author.id): raise UserNotSubscribedException() if len(params) < 2 or params[0][0] != '#': raise CommandSyntaxException() survey_id = params[0][1:] if not survey_id.isdigit(): raise InvalidSurveyIdException(survey_id) if not survey_id_is_valid(data, survey_id): raise InvalidSurveyIdException(survey_id) survey_data = data[survey_id] if message.author.id in survey_data['voted']: raise AlreadyVotedException() answers = [e.lower().strip() for e in params[1:]] if len(answers) > data[survey_id]['max_answers']: raise TooManyAnswersException(data[survey_id]['max_answers']) invalid_answers = check_answers(answers, len(survey_data['answers'])) if invalid_answers: raise AnswerNotFoundException(invalid_answers, survey_data['answers']) vote(message.author.id, survey_id, answers) embed = success embed.description = f'Danke für deine Teilnahme!\n' \ f'Du kannst die Ergebnisse mit\n' \ f'{cfg.options["invoke_normal"]}result #{survey_id} sehen.' except UserNotSubscribedException as e: embed.description = f'You have to be subscribed to participate. Use {cfg.options["invoke_normal"]}sub True' except AnswerNotFoundException as e: embed.description = f'Invalid answers: {e.invalid_answers}\nPossible answers: 1-{e.max_index}' except AlreadyVotedException as e: embed.description = 'You cannot vote twice.' except SurveyNotFoundException as e: embed.description = f'#{e.survey_id} could not be assigned to a survey.' except InvalidSurveyIdException as e: embed.description = f'{e.survey_id} is an invalid ID.' except CommandSyntaxException as e: embed.description = f'Invalid syntax.\nPlease use {cfg.options["invoke_normal"]}answer #survey_id Answer' except TooManyAnswersException as e: embed.description = f'Too many answers.\nYou are only allowed to give up to {e.max_answers} answers' finally: await message.channel.send(embed=embed)
async def main(client, message, params): success = SuccessEmbed(title="I am") error = NoticeEmbed(title="I am") roles = cfg.options["roles"] lower_roles = [e.lower() for e in list(roles.values())] want_role = ' '.join(params).strip().lower() if want_role in lower_roles: assign_role = list(roles.values())[lower_roles.index(want_role)] role = get(client.get_guild(message.guild.id).roles, name=assign_role) if role not in message.author.roles: await message.author.add_roles(role) success.description = f"Role {role.name} added." await message.channel.send(embed=success) else: await message.author.remove_roles(role) success.description = f"Role {role.name} removed." await message.channel.send(embed=success) else: error.description = "Please use one of these roles:"\ ' ```\n' + '\n'.join(list(roles.values())) + ' ```' await message.channel.send(embed=error)
async def main(client, message, params): files_failed = cfg.reload(debug=True) if files_failed == 0: embed = SuccessEmbed('Success', 'All files reloaded') else: embed = WarningEmbed('Reloading failed', f'Failed to reload {files_failed} file(s)') roles = cfg.options["roles_stats"].values() # creates basic table structures if not already present DB.create_structure(roles) # updates table structure, e.g. if a new role has been added DB.update_columns(roles) await message.channel.send(embed=embed)
async def end_discussion(args): client = args[0] data = handleJson.read_json_raw(path) if data["arena_status"] == "running": SHL.output("Ended discussion") SHL.output("Started poll") channel = client.get_channel(cfg.options["channel_ids"]["arena"]) role = get(channel.guild.roles, id=cfg.options["arena_role"]) embed = InfoEmbed(title="Arena - End", description="Arena stopped. Thank you for your participation") for m in data["participants"]: try: member = channel.guild.get_member(m) await member.remove_roles(role) await member.send(embed=embed) except: pass embed = SuccessEmbed(title="Arena - End") if len(data["participants"]) == 2: embed.description = "Ended discussion.\n Please vote for:\n"\ f"1⃣ {data['participants_name'][0]}\n" \ f"2⃣ {data['participants_name'][1]}\n" emojis = ['1⃣', '2⃣'] elif len(data["participants"]) == 4: embed.description = "Ended discussion.\n Please vote for:\n" \ f"1⃣ {data['participants_name'][0]}\n" \ f"2⃣ {data['participants_name'][1]}\n" \ f"3⃣ {data['participants_name'][2]}\n" \ f"4⃣ {data['participants_name'][3]}\n" emojis = ['1⃣', '2⃣', '3⃣', '4⃣'] close = await channel.send(embed=embed) data["last_poll_msg"] = close.id for e in emojis: await close.add_reaction(e) data["arena_status"] = "poll" handleJson.saveasjson(path, data)
async def announce_participant(args): client = args[0] data = handleJson.read_json_raw(path) if data["arena_status"] == "wait_queue": SHL.output("Announced participant") channel = client.get_channel(cfg.options["channel_ids"]["arena"]) embed = InfoEmbed(title="Arena - Participation", description="You are participating in the next discussion!") count = 0 data["participants"] = [] data["participants_name"] = [] shuffle(data["queue"]) for m in set(data["queue"]): if count >= data["participant_count"]: break try: member = channel.guild.get_member(m) await member.send(embed=embed) count += 1 data["participants"].append(member.id) data["participants_name"].append(member.display_name) except: # not a valid participant as he declined dm continue if len(data["participants"]) < data["participant_count"]: error = NoticeEmbed(title="Arena - Queue", description="Could not find enough members in queue.") channel.send(error) return data["queue"] = [] embed = SuccessEmbed(title="Arena - Participants", description="Participants:\n" + ",\n".join(data["participants_name"]) + "\n\nStart: Saturday 17:00") await channel.send(embed=embed) data["arena_status"] = "wait_start" handleJson.saveasjson(path, data)
async def main(client, message, params): def message_check(m): return m.channel == message.channel and message.author == m.author await message.channel.send('Title:') msg = await client.wait_for('message', check=message_check) title = msg.content await message.channel.send('Text:') msg = await client.wait_for('message', check=message_check) text = msg.content await message.channel.send('Do you want to supply a url?(y/n)') msg = await client.wait_for('message', check=message_check) choice = msg.content if choice.lower()[0] == 'y': await message.channel.send('Url:') msg = await client.wait_for('message', check=message_check) url = msg.content else: url = 'https://github.com/bundestagsBot/bundestagsBot' await message.channel.send('Type +finish once you\'re done') answers = [] while True: await message.channel.send(f'Answer#{len(answers) + 1}:') msg = await client.wait_for('message', check=message_check) answer = msg.content.strip() if answer == "+finish": break else: answers.append(answer) await message.channel.send('How many answers is a user allowed to give?') while True: try: msg = await client.wait_for('message', check=message_check) max_answers = int(msg.content) except ValueError: await message.channel.send("Invalid input. Please try again") else: break answers = dict(enumerate(answers, 1)) survey_id = get_survey_id() embed = create_survey(title, text, message.author, answers, max_answers, url, survey_id) msg = await message.channel.send(embed=embed) await msg.add_reaction('✅') await msg.add_reaction('❌') def reaction_check(reaction, user): e = str(reaction.emoji) return user == message.author and e.startswith(('✅', '❌')) reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=reaction_check) await msg.delete() if str(reaction.emoji).startswith('❌'): return # if approved add to json and send embed to all discord members who are not unsubscribed: data = handleJson.readjson(path) data[survey_id] = {} data[survey_id]['title'] = title.strip() data[survey_id]['text'] = text.strip() data[survey_id]['author'] = str(message.author.name) data[survey_id]['author_id'] = message.author.id data[survey_id]['url'] = url data[survey_id]['voted'] = [] data[survey_id]['max_answers'] = max_answers data[survey_id]['answers'] = answers data[survey_id]['results'] = {} for a in range(1, len(data[survey_id]['answers']) + 1): # so answers will be displayed sorted data[survey_id]['results'][a] = 0 data['latestID'] += 1 handleJson.saveasjson(path, data) # send to subscribers: members = client.get_guild(message.guild.id).members unsubs = handleJson.read_json_raw(subs_path)['unsubs'] received, failed = 0, 0 for m in [e for e in members if e.id not in unsubs]: try: received += 1 await m.send(embed=embed) except: failed += 1 success = SuccessEmbed(title='Publicsurvey') success.description = f'Umfrage an {received-failed} Personen gesendet.\n' \ f'{failed} Personen haben die Nachricht abgelehnt.' await message.channel.send(embed=success)
async def main(client, message, params): data = handleJson.read_json_raw(path) if not len(message.mentions): error = NoticeEmbed(title="Challenge", description="Please mention someone.") await message.channel.send(embed=error) return if message.mentions[0].id == message.author.id: error = NoticeEmbed(title="Challenge", description="You cannot challenge yourself.") await message.channel.send(embed=error) return if data["arena_status"]: notice = NoticeEmbed(title="Challenge", description="There is already a discussion running!") await message.channel.send(embed=notice) return data["participants"] = [] try: participants = message.mentions challenge = InfoEmbed(title="Challenge", description=f"Hey {participants[0].mention}" f"\n{message.author.mention} challenged you!") msg = await message.channel.send(embed=challenge) except: error = NoticeEmbed(title="Challenge", description="Something went wrong. Please contact an admin.") await message.channel.send(embed=error) return await msg.add_reaction('✅') await msg.add_reaction('❌') def check(reaction, user): e = str(reaction.emoji) return user == participants[0] and e.startswith(('✅', '❌')) and reaction.message.id == msg.id try: reaction, user = await client.wait_for('reaction_add', timeout=30.0, check=check) except TimeoutError: return if str(reaction.emoji).startswith('❌'): return data["arena_status"] = 1 try: info = InfoEmbed(title="Challenge", description=f"{participants[0].display_name} accepted your challenge!\n" + f'Discuss here: <#{cfg.options["channel_ids"]["1v1"]}>\n' f"Channel will be closed in {cfg.options['1v1_time_minutes']} minutes.") await message.author.send(embed=info) except: pass try: info = InfoEmbed(title="Challenge", description=f"You accepted {message.author.mention}s challenge.!\n" + f'Discuss here: <#{cfg.options["channel_ids"]["1v1"]}>\n' f"Channel will be closed in {cfg.options['1v1_time_minutes']} minutes.") await participants[0].send(embed=info) except: pass SHL.output(f"{participants[0].display_name} accepted {message.author.display_name}s challenge!") channel = client.get_channel(cfg.options["channel_ids"]["1v1"]) role = get(channel.guild.roles, id=cfg.options["1v1_role"]) await message.author.add_roles(role) await participants[0].add_roles(role) announce = SuccessEmbed(title="Challenge", description="Discussion duel started!\n" f"Battle between {message.author.mention} - {message.mentions[0].mention}\n" f"Channel will be closed in {cfg.options['1v1_time_minutes']} minutes.") await channel.send(embed=announce) data["participants"] = [message.author.id, participants[0].id] handleJson.saveasjson(path, data) await channel.edit(topic=f"Battle between: {message.author.mention} - {message.mentions[0].mention}") schedule_job(close_channel, cfg.options["1v1_time_minutes"], "challenge", client)