import os import json from datetime import datetime, timedelta import discord from discord.utils import get from bt_utils.console import Console from bt_utils.config import cfg from bt_utils.embed_templates import InfoEmbed SHL = Console("ActiveUserAssigment") content_dir = "content" if os.path.isdir("content") else "content-default" class UserStat: def __init__(self, user_obj: discord.Member): self.user_obj = user_obj self.count = 1 def __str__(self): return f"{self.user_obj.display_name}: {self.count}" async def assign_active_member(*args): SHL.info("Fetching last messages.") client = args[0] guild = await client.fetch_guild(cfg.get("guild_id")) SHL.debug(f"Guild: {guild}") # Remove all "active" members
import os.path from bt_utils.console import Console from bt_utils.embed_templates import SuccessEmbed from bt_utils import handleJson from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Queue") settings = { 'name': 'queue', 'channels': ['dm', 'bot'], } path = os.path.join(content_dir, "arena.json") 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)
import datetime import discord from bt_utils.console import Console from bt_utils.embed_templates import NoticeEmbed from bt_utils.config import cfg SHL = Console("BundestagsBot Survey") settings = { "name": "survey", "channels": ["!dm"], } async def main(client, message, params): args = " ".join(params).split(';') # used as discriminator is ";" here error = NoticeEmbed(title="Survey") if len(args) in range(2, 4): embed = create_survey(args[0], args[1], message.author) if len(args) == 3 and args[2] != '': args[2] = args[2].strip() if args[2].isdigit(): msg = await message.channel.send(embed=embed) if int(args[2]) in range(3, 10): emojis = [ '1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣' ] for e in emojis[:int(args[2])]:
from bt_utils.console import Console from bt_utils import handleJson import discord import datetime from discord.utils import get SHL = Console("BundestagsBot PublicSurvey") settings = { 'name': 'publicsurvey;', 'mod_cmd': True, 'channels': ['team1'], } ''' syntax: >publicsurvey title text [answers] {url} answers is a list of possible answers seperated by ',' url is optional and is autofilled with the github link waits for approve via discord reaction sends survey to all discord members they will use >answer survey_id their_answer they can unsubscribe via: >sub False or resubscribe: >sub True
from bt_utils.console import Console from bt_utils import handleJson from discord.utils import get import discord import datetime SHL = Console("BundestagsBot Respond") settings = { 'name': 'respond', 'channels': ['team1'], 'mod_cmd': True, 'log': True } path = 'content/submits.json' 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)
from bt_utils.console import Console import discord SHL = Console("BundestagsBot Help") settings = { 'name': 'help', 'channels': ['dm', 'bot'], } async def main(client, message, params): if len(params) == 0: embed = helpembed() elif params[0] == 'survey': embed = surveyhelpembed() else: embed = helpembed() await message.channel.send(embed=embed) def helpembed(): embed = discord.Embed(title='Hilfe - BundestagsBot v1', color=discord.colour.Colour.orange()) embed.set_thumbnail( url= 'https://cdn0.iconfinder.com/data/icons/handdrawn-ui-elements/512/Question_Mark-512.png' ) embed.description = '-Benutze >survey Titel; Beschreibung; <Anzahl>\num eine Umfrage zu erstellen. >help survey für mehr Details\n\n'\ '-Benutze >iam [Politik] um dir diese Rolle zuzuweisen.\n\n'\ '-Benutze >roles für eine Übersicht der Rollenverteilung.\n\n'\
from bt_utils.console import Console from bt_utils.config import cfg SHL = Console('BundestagsBot Reload') settings = {'name': 'reload', 'channels': ['team1'], 'mod_cmd': True} async def main(client, message, params): files_failed = cfg.reload(debug=True) if files_failed == 0: await message.channel.send(content='All files reloaded') else: await message.channel.send( content=f'Failed to reload {files_failed} file(s)')
from bt_utils.console import Console from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.cache_handler import cache from datetime import datetime import requests from discord import Embed, Colour SHL = Console("BundestagsBot Umfrage") settings = { 'name': 'umfrage', 'channels': ['dm', 'bot'], } async def main(client, message, params): api_cache = cache.get_data(key="dawum_api") data = api_cache.get("data", {}) timestamp = api_cache.get("timestamp", "") # if cache invalid if timestamp != datetime.now().strftime( "%Y.%m.%d") or data == {} or not cfg.options.get( "use_cache", True): try: data = requests.get('https://api.dawum.de/').json() except: SHL.output("Something went wrong while loading the request.") data = {} # write in cache cache.write_to_cache(data, key="dawum_api")
from bt_utils.console import Console from bt_utils import handleJson SHL = Console("BundestagsBot Answer") settings = {'name': 'answer', 'channels': ['dm'], 'log': False} path = 'content/surveys.json' 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=
import os.path from asyncio import TimeoutError from discord.utils import get from bt_utils.console import Console from bt_utils.embed_templates import SuccessEmbed, InfoEmbed, NoticeEmbed from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.get_content import content_dir from others.scheduler import schedule_job, clear_tag SHL = Console("BundestagsBot Challenge") settings = { 'name': 'challenge', 'channels': ['!dm'], } path = os.path.join(content_dir, "challenge.json") 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"]):
import os.path from bt_utils.console import Console from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Template Command") # Use SHL.output(text) for all console based output! settings = { 'name': 'template', # name/invoke of your command 'mod_cmd': True, # if this cmd is only useable for users with the teamrole 'channels': ['team'], # allowed channels: [dm, bot, team, all]; use !dm to blacklist dm 'log': True, # if this cmd should be logged to the console, default: True } # global / changeable variables PATH = os.path.join(content_dir, "template.json") # client, message object # params is a list of the message content splitted at spaces async def main(client, message, params): pass
from bt_utils.console import Console from bt_utils.embed_templates import ErrorEmbed, InfoEmbed from discord import Embed, Colour import datetime import os.path SHL = Console("BundestagsBot Post") settings = { 'name': 'post', 'mod_cmd': True, 'channels': ['team'], } suffix_text = """ Bei Fragen lest euch bitte die Regeln durch. Rehabilitationen sind möglich, wendet euch hierfür bitte an einen Moderator. """ async def main(client, message, params): try: target_channel = message.channel_mentions[0] text = " ".join(params[1:]) except IndexError: embed = ErrorEmbed( "Post", description="Syntax error\nUse `+post <#channel_id> text`") await message.channel.send(embed=embed) return embed = InfoEmbed(title="Moderation",
import os from bt_utils.console import Console from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.handle_sqlite import DatabaseHandler SHL = Console("Reset") DB = DatabaseHandler() def reset_file(path, data): try: handleJson.saveasjson(path, data) except FileNotFoundError: SHL.output("File not found. Creating it.") file_dir = os.path.join(handleJson.BASE_PATH, os.path.dirname(path)) if not os.path.exists(file_dir): os.makedirs(file_dir) handleJson.saveasjson(path, data) def reset(): # content folder # ================================================ content = os.path.join(handleJson.BASE_PATH, "content") if not os.path.exists(content): SHL.output("Creating content folder.") os.makedirs(content) SHL.output("Resetting challenge.json")
import subprocess from bt_utils.console import Console, blue2, white, red, yellow from bt_utils.embed_templates import InfoEmbed, ErrorEmbed SHL = Console("BundestagsBot Version") settings = { 'name': 'version', 'channels': ['dm', 'bot'], } try: git_version_short_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip() git_version_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() git_remote_url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('ascii').strip().replace(".git", "") if git_remote_url.startswith("git@"): __git_remote_host = git_remote_url[4:git_remote_url.index(":")] __git_remote_repo = git_remote_url[git_remote_url.index(":")+1:] git_remote_url = "https://" + __git_remote_host + "/" + __git_remote_repo SHL.output(f"{blue2}Found local version: {git_version_short_hash}, Git over SSH{white}") __generated_link = git_remote_url + "/commits/" + git_version_hash __msg = f"Current Version is {__generated_link}" elif git_remote_url.startswith("https://"): git_remote_url.replace(".git", "")
from bt_utils.console import Console import discord from bt_utils import handleJson SHL = Console("BundestagsBot Sub") settings = { 'name': 'sub', 'channels': ['dm', 'bot'], } path = 'content/surveys.json' async def main(client, message, params): 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) await message.channel.send(content='Done.') else: # unsubs subs(False, message.author.id) await message.channel.send( content= 'Done.\nDu kannst die Umfragen wieder abonnieren mit >sub True' ) else: await message.channel.send( content='Ungültiges Argument. Verwende: >sub True|False') else:
from bt_utils.console import Console from bt_utils.handle_sqlite import DatabaseHandler from bt_utils.config import cfg from bt_utils.embed_templates import NoticeEmbed, InfoEmbed SHL = Console("BundestagsBot Reactions") DB = DatabaseHandler() settings = { 'name': 'reactions', 'channels': ['all'], } async def main(client, message, params): if not len(message.mentions): embed = NoticeEmbed(title="Reactions", description=message.author.mention + 'Bitte einen Nutzer angeben') await message.channel.send(embed=embed) return data = DB.get_specific_user(message.mentions[0].id) if data: header = 'Reaktionen zu Nachrichten von ' + message.mentions[0].display_name + '\n' content = '' # skip name and id for i, role in enumerate(cfg.options["roles_stats"].items(), 1): if data[i] > 0: emoji_id = role[0] emoji_obj = await message.guild.fetch_emoji(emoji_id) emoji_str = "<:" + emoji_obj.name + ":" + emoji_id + ">" content += "" + emoji_str + ": " + str(data[i]) + "\n"
from datetime import datetime from discord import Embed, Color from bt_utils.config import cfg from bt_utils.console import Console, red, white SHL = Console("WelcomeEmbed") welcome_de = """ Unter <#{}> kannst du dir Rollen zuweisen. Beispielsweise Themen, die dich interessieren, oder deine politische Ausrichtung Oder sag doch einfach in <#{}> hallo :smiley: In <#{}> kannst du den Bot verwenden. Versuche doch mal `>umfrage` um aktuelle Wahlumfragen zu sehen :) Gerne kannst du mir hier mit `>submit text` ein Feedback oder ein Hinweis hinterlassen, die ich anonym ans Serverteam weiterleite. Wenn du Themen öffentlich ansprechen willst, kannst du das aber auch gerne in <#{}> tun. Lies dir bitte alle Regeln und Ankündigungen in <#{}> und <#{}> durch. Beteilige dich gerne an der Entwicklung des BundestagsBot:\n https://github.com/bundestagsBot/bundestagsBot """ def create_embed(lang="de"): embed = Embed(title=f'Willkommen!',
from discord.utils import get from bt_utils.console import Console from bt_utils.embed_templates import SuccessEmbed, NoticeEmbed from bt_utils.config import cfg SHL = Console("BundestagsBot Iam") settings = { 'name': 'iam', 'channels': ['bot'], } 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)
from bt_utils.console import Console from bt_utils.config import cfg import discord import datetime from discord.utils import get SHL = Console("BundestagsBot Roles") settings = { 'name': 'roles', 'channels': ['bot'], } async def main(client, message, params): roles = cfg.options["roles_show"] embed = discord.Embed(title='Rollen Übersicht', color=discord.colour.Colour.orange()) desc = 'Insgesamt hat der Server ' + str(client.get_guild(531445761733296130).member_count) + ' Mitglieder.\n\n' for r in [e for e in roles if e != 'nsfw']: role = get(client.get_guild(531445761733296130).roles, name=r.capitalize()) desc += role.name + ': ' + str(len(role.members)) + '.\n' embed.description = desc embed.timestamp = datetime.datetime.utcnow() await message.channel.send(embed=embed)
from bt_utils.console import Console from discord.utils import get SHL = Console("BundestagsBot Warn") settings = { 'name': 'warn', 'mod_cmd': True, } async def main(client, message, params): badbois = str(message.content)[5:].strip() for member in client.get_all_members(): if member.mention == badbois: badboi = member warned = get(client.get_guild(531445761733296130).roles, name='ErsteVerwarnung') in badboi.roles if not warned: await message.channel.send(content=badboi.mention + ' verwarnt!') punishrole = get(client.get_guild(531445761733296130).roles, id=533336650139435021) await badboi.add_roles(punishrole) else: await message.channel.send( content='Benutzer wurde bereits einmal verwarnt!')
import os from bt_utils.console import Console from bt_utils.embed_templates import SuccessEmbed, ErrorEmbed, NoticeEmbed, InfoEmbed from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.custom_exceptions import * from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Result") settings = { 'name': 'result', 'channels': ['all'], } path = os.path.join(content_dir, "surveys.json") async def main(client, message, params): embed = ErrorEmbed(title="Result") embed.description = "Something went wrong. Please contact an admin." try: if len(str(message.content).split(' ')) != 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(survey_id): raise SurveyNotFoundException(survey_id) embed = create_embed(survey_id)
import time from datetime import datetime import schedule from bt_utils.console import Console from bt_utils.config import cfg SHL = Console("Scheduler") x = cfg.get("daily_schedule", "01:00") SHL.info(f"Register daily jobs for {x}") class Scheduler: main_loop = None def starter(self, f, args=None): self.main_loop.create_task(f(args)) def monthly_starter(self, f, args=None): if datetime.now().day == 1: self.main_loop.create_task(f(args)) def clear_tag(self, tag): schedule.clear(str(tag)) def schedule_daily(self, func, tag, args=None): schedule.every().day.at(x).do(self.starter, func, args).tag(str(tag)) def schedule_monthly(
import os.path from bt_utils.console import Console from bt_utils.config import cfg from bt_utils.embed_templates import InfoEmbed, NoticeEmbed from bt_utils import handleJson from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Resolve") settings = { 'name': 'resolve', 'channels': ['team'], 'mod_cmd': True, 'log': True } path = os.path.join(content_dir, "submits.json") async def main(client, message, params): error = NoticeEmbed(title="Resolve") info = InfoEmbed(title="Resolve") if len(str(message.content).split(' ')) == 2: submit_id = params[0][1:] if submit_id.isdigit(): data = handleJson.read_json_raw(path) if submit_id in data.keys(): info.description = f"Anfrage #{submit_id} ist von:\n" \ f"{data[submit_id]['author']}\n" \ f"{data[submit_id]['authorID']}"
from random import shuffle import os.path from discord.utils import get from bt_utils.console import Console from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.embed_templates import SuccessEmbed, InfoEmbed, NoticeEmbed from bt_utils.get_content import content_dir SHL = Console("Arena") path = os.path.join(content_dir, "arena.json") # start discussion async def start_discussion(args): client = args[0] data = handleJson.read_json_raw(path) if data["arena_status"] == "wait_start": SHL.output("Started discussion") channel = client.get_channel(cfg.options["channel_ids"]["arena"]) role = get(channel.guild.roles, id=cfg.options["arena_role"]) embed = InfoEmbed(title="Arena", description="Arena started. Be sure to participate in the discussion!") for m in data["participants"]: member = channel.guild.get_member(m) await member.add_roles(role) await member.send(embed=embed)
import os from discord.utils import get from bt_utils.console import Console from bt_utils.embed_templates import WarningEmbed, SuccessEmbed, InfoEmbed from bt_utils.config import cfg from bt_utils import handleJson from bt_utils.get_content import content_dir SHL = Console("BundestagsBot Submit") settings = {'name': 'submit', 'channels': ['dm'], 'log': False} path = os.path.join(content_dir, "submits.json") 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",
import os.path import json from bt_utils.console import Console from bt_utils.get_content import content_dir from bt_utils.embed_templates import InfoEmbed, SuccessEmbed SHL = Console("BundestagsBot Analyze" ) # Use SHL.output(text) for all console based output! settings = { 'name': 'analyze', # name/invoke of your command 'mod_cmd': False, # if this cmd is only useable for users with the teamrole 'channels': ['all'], # allowed channels: [dm, bot, team, all]; use !dm to blacklist dm 'log': True, # if this cmd should be logged to the console, default: True } about_embed = InfoEmbed(title="Help") with open(os.path.join("static", "info.txt"), "r", encoding="utf-8") as fh: about_embed.description = fh.read() 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