def __init__(self, bot: Bot): self.bot: Bot = bot self.handles: dict = {} if not hasattr(bot, "lavalink"): bot.lavalink = lavalink.Client(bot.user.id) bot.ksoftapi = ksoftapi.Client(api_key=os.getenv("KSOFT")) host = os.getenv("LAVALINK_HOST", "localhost") port = int(os.getenv("LAVALINK_PORT", "4437")) password = os.getenv("LAVALINK_PASS") bot.lavalink.add_node(host=host, port=port, password=password, region="us", name="DEFAULT US") bot.lavalink.add_node(host=host, port=port, password=password, region="eu", name="DEFAULT EU") bot.lavalink.add_node(host=host, port=port, password=password, region="asia", name="DEFAULT ASIA") bot.add_listener(bot.lavalink.voice_update_handler, "on_socket_response") if len(bot.lavalink._event_hooks["Generic"] ) == 0: # Seems something is going wrong with cog_unload lavalink.add_event_hook(self.track_hook, self.autoplay_hook)
def __init__(self, bot: Life) -> None: self.bot = bot self.bot.lavalink = client.Client(bot=self.bot, session=self.bot.session) self.bot.spotify = spotify.Client(client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.bot.spotify_http = spotify.HTTPClient(client_id=self.bot.config.spotify_app_id, client_secret=self.bot.config.spotify_secret) self.bot.ksoft = ksoftapi.Client(self.bot.config.ksoft_token)
async def get_lyrics(self, ctx, *, query: str): """Get lyrics of current song""" kclient = ksoftapi.Client(os.environ['Kclient']) try: async with ctx.typing(): results = await kclient.music.lyrics(query) except ksoftapi.NoResults: await ctx.send(f'No lyrics found for `{query}`') else: lyrics = results[0].lyrics result = results[0] embed = discord.Embed(title=f'{result.name} - {result.artist}', color=discord.Color(0xCCFF00), description=lyrics[:2048]) embed.set_thumbnail(url=result.album_art) embed.set_author(name="Lyrics:") lyrics = lyrics[2048:] embeds = [embed] # create embeds' list for long lyrics while len(lyrics) > 0 and len( embeds) < 10: # limiting embeds to 10 embed = discord.Embed(color=discord.Color(0xCCFF00), description=lyrics[:2048]) lyrics = lyrics[len(embeds) * 2048:] embeds.append(embed) embeds[-1].set_footer( text="Source: KSoft.Si") # set footer for last embed for embed in embeds: await ctx.send(embed=embed)
async def start(self, *args, **kwargs): # noqa: C901 """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. Raises ------- TypeError An unexpected keyword argument was received. """ bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) await self.db.load() logging.info("bot:Loading KSoft Client") self.ksoft = ksoftapi.Client(os.getenv("KSOFT")) logging.info("bot:Loaded KSoft Client") if kwargs: raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys())) for i in range(0, 6): try: await self.login(*args, bot=bot) break except aiohttp.client_exceptions.ClientConnectionError as e: logging.warning(f"bot:Connection {i}/6 failed") logging.warning(f"bot: {e}") logging.warning(f"bot: waiting {2 ** (i + 1)} seconds") await asyncio.sleep(2**(i + 1)) logging.info("bot:attempting to reconnect") else: logging.error("bot: FATAL failed after 6 attempts") return for cog in self.cogs: cog = self.get_cog(cog) if not cog.description and cog.qualified_name not in self.cog_groups[ "Hidden"]: logging.error(f"bot:cog {cog} has no description") return missing_brief = [] for command in self.commands: if not command.brief: missing_brief.append(command) if missing_brief: logging.error("bot:the following commands are missing help text") for i in missing_brief: logging.error(f"bot: - {i.cog.qualified_name}.{i.name}") return await self.connect(reconnect=reconnect)
def __init__(self, bot: Life) -> None: self.bot = bot self.slate = slate.Client(bot=self.bot) self.spotify = spotify.Client( client_id=self.bot.config.spotify_client_id, client_secret=self.bot.config.spotify_client_secret) self.spotify_http = spotify.HTTPClient( client_id=self.bot.config.spotify_client_id, client_secret=self.bot.config.spotify_client_secret) self.ksoft = ksoftapi.Client(self.bot.config.ksoft_token)
async def on_ready(): print('Connecté comme {0} ({0.id})'.format(bot.user)) bot.kclient = ksoftapi.Client(os.environ['KSoft_Token']) bot.client = ClientSession() # Load Modules modules = ['debug', 'games', 'media', 'misc', 'music'] try: for module in modules: bot.load_extension('cogs.' + module) print('Loaded: ' + module) except Exception as e: print(f'Error loading {module}: {e}') print('Bot.....Activated') await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name="réviser les maths"))
async def lyrics(self, ctx: utils.CustomContext, *, song_name: str): """Get the lyrics to any given song, if the song is found.""" ksoft = ksoftapi.Client(self.bot.settings["keys"]["ksoft_api"]) try: results = await ksoft.music.lyrics(song_name) except ksoftapi.NoResults: return await ctx.send(f"No lyrics found for {song_name}.") await ksoft.close() first = results[0] lyrics = first.lyrics.splitlines() source = LyricsPaginator(lyrics) menu = utils.KalPages(source) await menu.start(ctx)
async def on_ready(): print('Logged in as {0} ({0.id})'.format(bot.user)) bot.kclient = ksoftapi.Client(os.environ['KSoft_Token']) bot.client = ClientSession() # Load Modules modules = ['music', 'fun', 'utility', 'meme', 'game', 'misc', 'debug'] try: for module in modules: bot.load_extension('cogs.' + module) print('Loaded: ' + module) except Exception as e: print(f'Error loading {module}: {e}') print('Bot.....Activated') await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name="Nothing"))
async def obtain_client(self): """Get a client and put it in self.client (For caching). Returns ------- ksoftapi.Client: Client to use, bound to self.client. Raises ------ AttributeError: If the API key was not set. """ if self.client: return self.client keys = await self.bot.get_shared_api_tokens("ksoftsi") if keys.get("api_key"): self.client = ksoftapi.Client(keys.get("api_key")) return self.client raise AttributeError("API key is not set.")
async def on_ready(): print('Connecté comme {0} ({0.id})'.format(bot.user)) bot.kclient = ksoftapi.Client(os.environ['Kclient']) bot.client = ClientSession() # Load Modules modules = [ 'debug', 'games', 'MCServ', 'media', 'misc', 'music', 'Random', 'weather', 'Unsplash' ] #'covid', try: for module in modules: bot.load_extension('cogs.' + module) print('Loaded: ' + module) except Exception as e: print(f'Error loading {module}: {e}') print('Bot.....Activated') await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name="Personnal test bot"))
def __init__(self, bot): self.bot = bot load_dotenv() self.kclient = ksoftapi.Client(os.getenv('KSOFT_API'))
# LastFM last_fm_api_key = os.getenv("LAST_API_KEY") last_fm_shared_secret = os.getenv("LAST_SHARED_SECRET") last_fm_root_url = os.getenv("LAST_ROOT_URL") last_fm_headers = {'user-agent': os.getenv("LAST_USER_AGENT")} # Patreon patreon_link = os.getenv("PATREON_LINK") patreon_role_id = make_int(os.getenv("PATREON_ROLE_ID")) patreon_super_role_id = make_int(os.getenv("PATREON_SUPER_ROLE_ID")) # startup time startup_time = datetime.now() # Aiohttp Client Session client_session = aiohttp.ClientSession() # Wolfram wolfram_app_id = os.getenv("WOLFRAM_APP_ID") # Song Lyrics Client lyrics_api_key = os.getenv("LYRICS_API_KEY") if len(lyrics_api_key) != 0: lyric_client = ksoftapi.Client(lyrics_api_key) else: lyric_client = None # API api_port = os.getenv("API_PORT") translate_private_key = os.getenv("PRIVATE_KEY")
def __init__(self, bot): self.bot = bot self.bot.ksoft = ksoftapi.Client( api_key=bot.config['ksoft'] if not bot.dev else bot. config['ksoftalt'])
async def start(self, *args, **kwargs): # noqa: C901 """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. Raises ------- TypeError An unexpected keyword argument was received. """ bot = kwargs.pop('bot', True) # noqa f841 reconnect = kwargs.pop('reconnect', True) self.db = AoiDatabase(self) self.banned_tags = os.getenv("BANNED_TAGS").split(",") self.gelbooru_user = os.getenv("GELBOORU_USER") self.gelbooru_key = os.getenv("GELBOORU_API_KEY") self.weather_gov = os.getenv("WEATHER_GOV_API") self.google = os.getenv("GOOGLE_API_KEY") self.nasa = os.getenv("NASA") self.accuweather = os.getenv("ACCUWEATHER") self.imgur_user = os.getenv("IMGUR") self.imgur_secret = os.getenv("IMGUR_SECRET") self.gmap = gmaps.GeoLocation(self.google) self.ksoft_api = os.getenv("KSOFT") self.twitter_bearer = os.getenv("TWITTER_BEARER") # self.pixiv.login(self.pixiv_user, self.pixiv_password) self.imgur = imgur.Imgur(self.imgur_user) await self.db.load() self.logger.info("Loading alias table") for row in await self.db.conn.execute_fetchall("select * from alias"): if row[0] not in self.aliases: self.aliases[row[0]] = {row[1]: row[2]} else: self.aliases[row[0]][row[1]] = row[2] self.logger.info("Loaded alias table") if kwargs: raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys())) for i in range(0, 6): try: self.logger.debug(f"bot:Connecting, try {i + 1}/6") await self.login(*args) break except aiohttp.client_exceptions.ClientConnectionError as e: self.logger.warning(f"bot:Connection {i + 1}/6 failed") self.logger.warning(f"bot: {e}") self.logger.warning(f"bot: waiting {2 ** (i + 1)} seconds") await asyncio.sleep(2 ** (i + 1)) self.logger.info("bot:attempting to reconnect") else: self.logger.critical("bot: failed after 6 attempts") return for cog in self.cogs: cog = self.get_cog(cog) if not cog.description and cog.qualified_name not in self.cog_groups["Hidden"]: self.logger.critical(f"bot:cog {cog.qualified_name} has no description") return for row in self.cog_groups.values(): for cog_name in row: if not self.get_cog(cog_name): self.logger.critical(f"bot:cog {cog_name} has no matching cog") return missing_brief = [] for command in self.commands: if not command.brief: missing_brief.append(command) if missing_brief: self.logger.error("bot:the following commands are missing help text") for i in missing_brief: self.logger.error(f"bot: - {i.cog.qualified_name}.{i.name}") return await generate(self) self.ksoft = ksoftapi.Client(self.ksoft_api, loop=self.loop) await self.connect(reconnect=reconnect)
import ksoftapi import discord from discord.ext import commands from main import KSoft_api client = ksoftapi.Client(api_key=KSoft_api) class Meme(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="meme") async def meme(self, ctx, arg1: str = None): if arg1 is None: img = await client.random_meme() embed = discord.Embed() embed.set_image(url=str(img.url)) await ctx.send(embed=embed) else: image = await client.random_image(tag=arg1, nsfw=False) if image.url is None: await ctx.send( "Couldnt find that tag, make sure you spelled it right, or maybe it just dosnt exist" ) else: embed = discord.Embed() embed.set_image(url=str(image.url)) embed.set_footer(text=str(image.snowflake))
import discord from discord.ext import commands import datetime import json import ksoftapi import typing import random from jishaku.paginators import WrappedPaginator, PaginatorEmbedInterface from fire.converters import Member print("ksoft.py has been loaded") with open('config.json', 'r') as cfg: config = json.load(cfg) client = ksoftapi.Client(api_key=config['ksoft']) def isadmin(ctx): """Checks if the author is an admin""" if str(ctx.author.id) not in config['admins']: admin = False else: admin = True return admin imgext = ('.png', '.jpg', '.jpeg', '.gif') class ksoft(commands.Cog, name="KSoft.SI API"): def __init__(self, bot): self.bot = bot self.bot.ksoft = client
import discord from discord.ext import commands import ksoftapi from utils import default config = default.get("config.json") kclient = ksoftapi.Client(config.ksoft_token) class KSoft(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def lyrics(self, ctx, *, query): """ Return lyrics for a given song """ try: results = await kclient.music.lyrics(query=query, clean_up=True) except ksoftapi.NoResults: await ctx.send('No lyrics found for ' + query) else: first = results[0] embed = discord.Embed( title=f"Lyrics for {first.name} by {first.artist}", description=first.lyrics) embed.set_footer(text="Lyrics provided by KSoft.Si") await ctx.send(embed=embed) @commands.command() async def meme(self, ctx): meme = await kclient.images.random_meme()
return commands.when_mentioned_or(config.default_prefix, "myaer ", "Myaer ")(bot, message) prefix = data.guilds.get_silent(message.guild.id).prefix or config.default_prefix return commands.when_mentioned_or(prefix, "myaer ", "Myaer ")(bot, message) bot = commands.Bot( command_prefix=get_prefix, owner_id=config.owner, allowed_mentions=discord.AllowedMentions(everyone=False, replied_user=False), intents=discord.Intents.all() ) bot.static = Static(bot) bot.config = config bot.data = data bot.mojang = hypixelaPY.Mojang() bot.ksoft = ksoftapi.Client(config.keys.ksoft) extensions = [os.path.join(dp, f) for dp, dn, fn in os.walk("cogs") for f in fn] + \ [os.path.join(dp, f) for dp, dn, fn in os.walk("commands") for f in fn] + \ [os.path.join(dp, f) for dp, dn, fn in os.walk("modules") for f in fn] + \ [os.path.join(dp, f) for dp, dn, fn in os.walk("events") for f in fn] + \ ["jishaku", "initialize"] for file in extensions[:]: if not file.endswith(".py") and file not in ["jishaku", "initialize"]: # jishaku cog is a special case extensions.remove(file) bot.static.failed_extensions = [] def load_extensions(): # this was purely done for the reason of variable scope for extension in extensions: try:
try: with open("C:\\Users\\alber\\OneDrive\\Plocha\\discordBotSecrets.txt", "r") as f: commands.kclient = eval(f.readline()) token = eval(f.readline()) commands.reddit = eval(f.readline()) botFunctions.githubToken = eval(f.readline()) except: with open("/home/bertik23/Plocha/discordBotSecrets.txt", "r") as f: commands.kclient = eval(f.readline()) token = eval(f.readline()) commands.reddit = eval(f.readline()) botFunctions.githubToken = eval(f.readline()) else: commands.kclient = ksoftapi.Client(os.environ.get("ksoft_token", None)) commands.reddit = praw.Reddit( client_id=os.environ.get("reddit_client_id", None), client_secret=os.environ.get("reddit_client_secret", None), user_agent=os.environ.get("reddit_user_agent", None)) token = os.environ.get('TOKEN', None) botId = 540563812890443794 #84032 permissions int #https://discordapp.com/oauth2/authorize?client_id=540563812890443794&scope=bot&permissions=8 client = discord.Client() botGames.client = client
def __init__(self, bot): self.client = None self.bot = bot self.kclient = ksoftapi.Client(KSoft_Token)