def createembed(survey_id): data = handleJson.readjson(path) title = data[survey_id]["title"] text = data[survey_id]["text"] author = data[survey_id]["author"] url = data[survey_id]["url"] votes = len(data[survey_id]["voted"]) answers = data[survey_id]["answers"] results = data[survey_id]["results"] embed = discord.Embed(title='Umfrage #' + str(survey_id) + ': ' + title, color=discord.Colour.green(), url=url) embed.timestamp = datetime.datetime.utcnow() embed.add_field(name='Frage:', value=text.replace('|', '\n'), inline=False) embed.add_field(name='Antwortmöglichkeiten:', value='1 - ' + str(answers)) embed.add_field(name='Beteiligung: ', value='Insgesamt abgestimmt haben: ' + str(votes)) embed.add_field(name='Ergebnis:', value='\n'.join([ f"{results[e]} Stimmen für: {e}" for e in results.keys() if results[e] != 0 ]), inline=False) embed.set_footer(text="Umfrage von " + author) return embed
def subs(sub, user_id): data = handleJson.readjson(path) if sub: if user_id in data["unsubs"]: data["unsubs"].remove(user_id) else: if user_id not in data["unsubs"]: data["unsubs"].append(user_id) handleJson.saveasjson(path, data)
def savejson(message): data = handleJson.readjson(path) id = int(data["latestID"]) + 1 data[id] = {} data[id]["author"] = str(message.author) data[id]["authorID"] = str(message.author.id) data[id]["text"] = ' '.join(str(message.content).split(' ')[1:]) data[id]["answer"] = "" data[id]["answerfrom"] = "" data["latestID"] += 1 handleJson.saveasjson(path, data) return id
def reload(self, debug=False): SHL.output(f"Reloading config.") files_failed = 0 for path in PATHS: SHL.output(f"Reloading configfile {BASE_PATH + path}") data = handleJson.readjson(BASE_PATH + path) if data is None: files_failed += 1 continue for key, value in data.items(): self.options[key] = value if debug: SHL.output(f"[{key}]: {value}") SHL.output(f"{red}========================{white}") return files_failed
async def main(client, message, params): params = [p for p in str(message.content).split(';')] if len(params) == 4 or params[4] == '': params.append('https://github.com/bundestagsBot/bundestagsBot') survey_id = get_survey_id() embed = createsurvey(params[1], params[2], message.author, params[3], params[4], survey_id) 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) 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"] = params[1].strip() data[survey_id]["text"] = params[2].strip() data[survey_id]["author"] = str(message.author.name) data[survey_id]["url"] = params[4] data[survey_id]["voted"] = [] data[survey_id]["answers"] = params[3].strip().lower() data[survey_id]["results"] = {} for a in range(1, int(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(531445761733296130).members unsubs = data['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 await message.channel.send(content='Done.\nUmfrage an ' + str(received-failed) + ' Personen gesendet.\n' + str(failed) + ' Personen haben die Nachricht abgelehnt.')
async def main(client, message, params): if len(str(message.content).split(' ')) == 2: id = str(message.content).split(' ')[1][1:] if id.isdigit(): data = handleJson.readjson(path) if id in data.keys(): await message.channel.send( content= f'Anfrage #{id} ist von:\n{data[id]["author"]}\n{data[id]["authorID"]}' ) else: await message.channel.send( content=f'{id} konnte keiner Anfrage zugeordnet werden') else: await message.channel.send(content=f'{id} ist keine gültige ID') else: await message.channel.send( content='Ungültige Anzahl an Argumenten. Versuche +resolve #id')
async def main(client, message, params): params = str(message.content).split(' ') if subscribed(message.author.id): if len(params) == 3: if params[1][1:].isdigit(): survey_id = params[1][1:] if surveyID_is_valid(survey_id): surveyData = handleJson.readjson(path)[survey_id] if message.author.id not in surveyData['voted']: if int(str(params[2]).lower().strip()) in range( 1, int(surveyData['answers']) + 1): vote(message.author.id, survey_id, params[2].lower().strip()) await message.channel.send( content= 'Danke für deine Antwort!\nDu kannst die Ergebnisse mit\n>result #' + survey_id + ' sehen.') else: await message.channel.send( content= 'Keine gültige Antwort.\nMögliche Antworten: 1-' + str(surveyData['answers'])) else: await message.channel.send( content='Du kannst nicht nochmal abstimmen.') else: await message.channel.send( content='#' + str(survey_id) + ' konnte keiner Umfrage zugeordnet werden.') else: await message.channel.send(content=str(params[1]) + ' ist keine gültige ID.') else: await message.channel.send( content= 'Ungültige Anzahl an Argumenten. Verwende:\n>answer #survey_id Antwort' ) else: await message.channel.send( content= 'Du musst die Umfragen abonniert haben, um abzustimmen. >sub True')
async def main(client, message, params): if len(str(message.content).split(' ')) >= 3: id = str(message.content).split(' ')[1][1:] if id.isdigit(): data = handleJson.readjson(path) if id in data.keys(): if data[id]["answer"] == "": embed = createembed(id, data, message) 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 authorID = data[id]["authorID"] submitauthor = get(client.get_guild(531445761733296130).members, id=int(authorID)) await submitauthor.send(embed=embed) await message.channel.send(content='Antwort abgeschickt!') data[id]["answer"] = ' '.join(str(message.content).split(' ')[2:]) data[id]["answerfrom"] = str(message.author) handleJson.saveasjson(path, data) else: await message.channel.send(content=f'#{id} wurde schon von {data[id]["answerfrom"]} mit \n'+ f'"{data[id]["answer"]}" beantwortet.') else: await message.channel.send(content=f'{id} konnte keiner Anfrage zugeordnet werden') else: await message.channel.send(content=f'{id} ist keine gültige ID') else: await message.channel.send(content='Ungültige Anzahl an Argumenten. Versuche +respond #id Antwort')
def get_survey_id(): return int(handleJson.readjson(path)['latestID']) + 1
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)
def surveyID_is_valid(survey_id): return str(survey_id) in [ key for key in handleJson.readjson(path).keys() if key not in ['unsubs', 'latestID'] ]
def subscribed(user_id): return user_id not in handleJson.readjson(path)['unsubs']
def vote(user_id, survey_id, answer): surveyData = handleJson.readjson(path) surveyData[survey_id]['voted'].append(user_id) surveyData[survey_id]['results'][answer] += 1 handleJson.saveasjson(path, surveyData)