async def get_user(user, mode): osu_collection = database[OsuC.osu_collection_name] if isinstance(user, int): cursor = osu_collection.find({'user_id': str(user)}) document = await cursor.to_list(length=1) try: document = document[0] user = document['osu_user'] except IndexError: return None regex = re.compile(r'^(?:http)s?://osu\.ppy\.sh/users/' ) # Regex to check if a link is provided if user.isdigit(): # If user provided an ID user = int(user) elif re.match(regex, user) is not None: # If user provided an link link_split = user.split('/') user_id = [i for i in link_split if i.isdigit()] # Get the user ID user = int(user_id[0]) # Convert ID into integer elif user.isalpha(): # If user provided a username pass if mode == 'taiko': # If taiko mode selected gamemode = enums.OsuMode.taiko elif mode == 'ctb' or mode == 'catch' or mode == 'fruits': # If catch the beat mode selected gamemode = enums.OsuMode.ctb elif mode == 'mania': # If mania mode selected gamemode = enums.OsuMode.mania else: # Set default gamemode gamemode = enums.OsuMode.osu api = OsuApi(OsuC.osu_key, connector=AHConnector()) # Connect to osu! API result = await api.get_user(user, mode=gamemode) try: user_data = result[0] except IndexError: user_data = None return user_data
import discord, random, os, string, requests from discord.ext import commands from discord.ext.commands import Bot from osuapi import OsuApi, ReqConnector osu_key = 'OSU_API_KEY_GOES_HERE' bot_key = 'DISCORD_BOT_KEY_GOES_HERE' api = OsuApi(osu_key, connector=ReqConnector()) bot = commands.Bot(command_prefix='dosu ') # If you're going to use the emojis that were pre-assigned to this bot, DM @boop#1692 to get you bot added to the server. # Also, A little credit pls <3 def changeToEmoji(letter): value = '' if letter == "A": value = "<:A_:463922386647908382>" elif letter == "S": value = '<:S_:463922496081625100>' elif letter == "SH": value = "<:S_:463922547382288385>" elif letter == "X": value = "<:SS:463922656668811265>" elif letter == "XH": value = "<:SS:463922701925613569>" elif letter == "B": value = "<:B_:464028170434248705>" elif letter == 'C':
load_dotenv() REDKEY = str(os.getenv('REDKEY')) REDSEC = str(os.getenv('REDSEC')) REDPASS = str(os.getenv('REDPASS')) OSUKEY = str(os.getenv('OSUKEY')) DISCKEY = str(os.getenv('DISCKEY')) GIFKEY = str(os.getenv('GIFKEY')) reddit = praw.Reddit(client_id=REDKEY, client_secret=REDSEC, username='******', password=REDPASS, user_agent='disc') api = OsuApi(OSUKEY, connector=ReqConnector()) x = '.' client = commands.Bot(command_prefix=x) client.remove_command('help') @client.event async def on_ready(): await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game('.help for commands!')) print("WE live boys can i get a pogU in the chat") @client.command() async def help(ctx): await ctx.send(f"""
class BaseTwitchPlugin: def __init__(self, bot): self.bot = bot self.bancho_queue = self.bot.config.get('bancho_queue') self.bancho_nick = self.bot.config.get('bancho_nick') self.osu = OsuApi(self.bot.config.get('osu_api_key'), connector=AHConnector()) tillerino_key = self.bot.config.get('tillerino_api_key') if tillerino_key: self.tillerino = TillerinoApi(tillerino_key) else: self.tillerino = None self.twitch_channel = self.bot.config.get('twitch_channel') if not self.twitch_channel.startswith('#'): self.twitch_channel = '#{}'.format(self.twitch_channel) @irc3.event(irc3.rfc.CONNECTED) def connected(self, **kw): self.bot.log.info('[twitch] Connected to twitch as {}'.format( self.bot.nick)) self.join(self.twitch_channel) def join(self, channel): self.bot.log.info('[twitch] Trying to join channel {}'.format(channel)) self.bot.join(channel) def part(self, channel): self.bot.log.info('[twitch] Leaving channel {}'.format(channel)) self.bot.part(channel) @asyncio.coroutine def _get_pp(self, beatmap, mods=OsuMod.NoMod): if self.tillerino: try: with async_timeout.timeout(15): data = yield from self.tillerino.beatmapinfo( beatmap.beatmap_id, mods=mods.value) if data: if 'starDiff' in data: # use Tillerino star rating since it factors in mods beatmap.difficultyrating = data['starDiff'] pp = { float(acc): pp_val for acc, pp_val in data.get('ppForAcc', {}).items() } if pp: beatmap.pp = pp return pp except (HTTPError, asyncio.TimeoutError) as e: self.bot.log.debug('[twitch] {}'.format(e)) beatmap.pp = None return None def validate_beatmaps(self, beatmaps, **kwargs): """Return subset of maps in beatmaps that pass validation criteria Raises: BeatmapValidationError if a map fails validation Override this method in subclasses as needed """ return beatmaps @asyncio.coroutine def _beatmap_msg(self, beatmap, mods=OsuMod.NoMod): if mods == OsuMod.NoMod: mod_string = '' else: mod_string = ' +{:s}'.format(mods) beatmap = self._apply_mods(beatmap, mods) # get pp before generating message since it may update star rating based on yield from self._get_pp(beatmap, mods=mods) msg = '[{}] {} - {} [{}] (by {}){}, ♫ {:g}, ★ {:.2f}'.format( beatmap.approved.name.capitalize(), beatmap.artist, beatmap.title, beatmap.version, beatmap.creator, mod_string, beatmap.bpm, round(beatmap.difficultyrating, 2), ) if beatmap.pp: msg = ' | '.join([ msg, '95%: {}pp'.format(round(beatmap.pp[.95])), '98%: {}pp'.format(round(beatmap.pp[.98])), '100%: {}pp'.format(round(beatmap.pp[1.0])), ]) return msg @asyncio.coroutine def _request_mapset(self, match, mask, target, mods=OsuMod.NoMod, **kwargs): try: with async_timeout.timeout(15): mapset = yield from self.osu.get_beatmaps( beatmapset_id=match.group('mapset_id'), include_converted=0) if not mapset: return (None, None) mapset = sorted(mapset, key=lambda x: x.difficultyrating) except (HTTPError, asyncio.TimeoutError) as e: self.bot.log.debug('[twitch] {}'.format(e)) return (None, None) try: beatmap = self.validate_beatmaps(mapset, **kwargs)[-1] except BeatmapValidationError as e: return (None, e.reason) msg = yield from self._beatmap_msg(beatmap, mods=mods) return (beatmap, msg) @asyncio.coroutine def _request_beatmap(self, match, mask, target, mods=OsuMod.NoMod, **kwargs): try: with async_timeout.timeout(10): beatmaps = yield from self.osu.get_beatmaps( beatmap_id=match.group('beatmap_id'), include_converted=0) if not beatmaps: return (None, None) except (HTTPError, asyncio.TimeoutError) as e: self.bot.log.debug('[twitch] {}'.format(e)) return (None, None) try: beatmap = self.validate_beatmaps(beatmaps, **kwargs)[0] except BeatmapValidationError as e: return (None, e.reason) msg = yield from self._beatmap_msg(beatmap, mods=mods) return (beatmap, msg) def _badge_list(self, badges): """Parse twitch badge ircv3 tags into a list""" b_list = [] for x in badges.split(','): (badge, version) = x.split('/', 1) b_list.append(badge) return b_list def _is_sub(self, privmsg_tags): """Check if twitch irc3 tags include sub (or mod) badge""" badges = self._badge_list(privmsg_tags.get('badges', '')) if any(b in badges for b in ['broadcaster', 'moderator', 'subscriber']): return True elif privmsg_tags.get('mod', 0) == 1: return True elif privmsg_tags.get('subscriber', 0) == 1: return True @asyncio.coroutine def _request_beatmapsets(self, match, mask, target, **kwargs): """Handle "new" osu web style beatmapsets links""" if match.group('beatmap_id'): return self._request_beatmap(match, mask, target, **kwargs) else: return self._request_mapset(match, mask, target, **kwargs) def _bancho_msg(self, mask, beatmap, mods=OsuMod.NoMod): m, s = divmod(beatmap.total_length, 60) if mods == OsuMod.NoMod: mod_string = '' else: mod_string = ' +{:s}'.format(mods) bancho_msg = ' '.join([ '{} >'.format(mask.nick), '[http://osu.ppy.sh/b/{} {} - {} [{}]]{}'.format( beatmap.beatmap_id, beatmap.artist, beatmap.title, beatmap.version, mod_string, ), '{}:{:02d} ★ {:.2f} ♫ {:g} AR{:g} OD{:g}'.format( m, s, round(beatmap.difficultyrating, 2), beatmap.bpm, round(beatmap.diff_approach, 1), round(beatmap.diff_overall, 1), ), ]) if beatmap.pp: bancho_msg = ' | '.join([ bancho_msg, '95%: {}pp'.format(round(beatmap.pp[.95])), '98%: {}pp'.format(round(beatmap.pp[.98])), '100%: {}pp'.format(round(beatmap.pp[1.0])), ]) return bancho_msg def _parse_mods(self, mods): mod_dict = { 'NF': OsuMod.NoFail, 'EZ': OsuMod.Easy, 'HD': OsuMod.Hidden, 'HR': OsuMod.HardRock, 'SD': OsuMod.SuddenDeath, 'DT': OsuMod.DoubleTime, 'RX': OsuMod.Relax, 'HT': OsuMod.HalfTime, 'NC': OsuMod.Nightcore, 'FL': OsuMod.Flashlight, 'SO': OsuMod.SpunOut, 'AP': OsuMod.Autopilot, 'PF': OsuMod.Perfect, } if (len(mods) % 2) != 0: mods = mods[:-1] mod_flags = OsuMod.NoMod for mod in [mods.upper()[i:i + 2] for i in range(0, len(mods), 2)]: mod_flags |= mod_dict.get(mod, OsuMod.NoMod) return mod_flags def _mod_ar(self, ar, ar_mul, speed_mul): ar0_ms = 1800 ar5_ms = 1200 ar10_ms = 450 ar_ms_step1 = (ar0_ms - ar5_ms) / 5.0 ar_ms_step2 = (ar5_ms - ar10_ms) / 5.0 ar_ms = ar5_ms ar *= ar_mul if ar < 5.0: ar_ms = ar0_ms - ar_ms_step1 * ar else: ar_ms = ar5_ms - ar_ms_step2 * (ar - 5.0) # cap between 0-10 before applying HT/DT ar_ms = min(ar0_ms, max(ar10_ms, ar_ms)) ar_ms /= speed_mul if ar_ms > ar5_ms: ar = (ar0_ms - ar_ms) / ar_ms_step1 else: ar = 5.0 + (ar5_ms - ar_ms) / ar_ms_step2 return ar def _mod_od(self, od, od_mul, speed_mul): od0_ms = 79.5 od10_ms = 19.5 od_ms_step = (od0_ms - od10_ms) / 10.0 od *= od_mul od_ms = od0_ms - math.ceil(od_ms_step * od) # cap between 0-10 before applying HT/DT od_ms = min(od0_ms, max(od10_ms, od_ms)) od_ms /= speed_mul od = (od0_ms - od_ms) / od_ms_step return od def _apply_mods(self, beatmap, mods=OsuMod.NoMod): """Return a copy of beatmap with difficulty modifiers applied""" if mods == OsuMod.NoMod: return beatmap modded = beatmap if (OsuMod.DoubleTime | OsuMod.Nightcore) in mods and OsuMod.HalfTime not in mods: speed_mul = 1.5 elif OsuMod.HalfTime in mods and (OsuMod.DoubleTime | OsuMod.Nightcore) not in mods: speed_mul = .75 else: speed_mul = 1.0 modded.bpm *= speed_mul if OsuMod.HardRock in mods and OsuMod.Easy not in mods: od_ar_hp_mul = 1.4 cs_mul = 1.3 elif OsuMod.Easy in mods and OsuMod.HardRock not in mods: od_ar_hp_mul = .5 cs_mul = .5 else: od_ar_hp_mul = 1.0 cs_mul = 1.0 modded.diff_approach = self._mod_ar(beatmap.diff_approach, od_ar_hp_mul, speed_mul) modded.diff_overall = self._mod_ar(beatmap.diff_overall, od_ar_hp_mul, speed_mul) modded.diff_drain = min(10.0, beatmap.diff_drain * od_ar_hp_mul) modded.diff_size = min(10.0, beatmap.diff_size * cs_mul) return modded @irc3.event(irc3.rfc.PRIVMSG) @asyncio.coroutine def request_beatmap(self, tags=None, mask=None, target=None, data=None, bancho_target=None, **kwargs): if not target.is_channel or not data: return patterns = [ (r'https?://osu\.ppy\.sh/b/(?P<beatmap_id>\d+)', self._request_beatmap), (r'https?://osu\.ppy\.sh/s/(?P<mapset_id>\d+)', self._request_mapset), (r'https?://osu\.ppy\.sh/beatmapsets/(?P<mapset_id>\d+)(#(?P<mode>[a-z]+))?(/(?P<beatmap_id>\d+))?', self._request_beatmapsets), ] for pattern, callback in patterns: mod_pattern = r'(/?\s*\+?(?P<mods>[A-Za-z]+))?' m = re.search(''.join([pattern, mod_pattern]), data) if m: if m.group('mods'): mod_flags = self._parse_mods(m.group('mods')) else: mod_flags = OsuMod.NoMod (beatmap, msg) = yield from callback(m, mask, target, mods=mod_flags, **kwargs) if beatmap: bancho_msg = self._bancho_msg(mask, beatmap, mods=mod_flags) if not bancho_target: bancho_target = self.bancho_nick yield from self.bancho_queue.put( (bancho_target, bancho_msg)) if msg: self.bot.privmsg(target, msg) break @command @asyncio.coroutine def stats(self, mask, target, args, default_user=None): """Check stats for an osu! player %%stats [<username>]... """ self.bot.log.debug('[twitch] !stats {}'.format(args)) if target.is_channel: dest = target else: dest = mask osu_username = '******'.join(args.get('<username>')).strip() if not osu_username: if default_user: osu_username = default_user else: osu_username = self.bancho_nick try: with async_timeout.timeout(10): users = yield from self.osu.get_user(osu_username) except (HTTPError, asyncio.TimeoutError) as e: self.bot.log.debug('[twitch] {}'.format(e)) users = [] if not users: self.bot.privmsg( dest, 'Could not find osu! user {}'.format(osu_username)) return user = users[0] msg = ' | '.join([ user.username, 'PP: {:,} (#{:,})'.format(user.pp_raw, user.pp_rank), 'Acc: {:g}%'.format(round(user.accuracy, 2)), 'Score: {:,}'.format(user.total_score), 'Plays: {:,} (lv{})'.format(user.playcount, math.floor(user.level)), 'https://osu.ppy.sh/users/{}'.format(user.user_id), ]) self.bot.privmsg(dest, msg)
def __init__(self, bot): self.bot = bot self.redis = bot.db.redis self.bot.say_edit = bot.says_edit self.api = OsuApi(utils.OS_Get("osu"), connector=AHConnector())
def __init__(self, bot): self.bot = bot if bot.config['osu']: self.api = OsuApi(bot.config['osu'], connector=AHConnector()) else: self.api = None
import requests from functions import * from osuapi import OsuApi, ReqConnector Token_read = open("token.txt") api_read = open("osuapikey.txt") TOKEN = Token_read.readline() apicode = api_read.readline() import json api = OsuApi(apicode, connector=ReqConnector()) client = commands.Bot(command_prefix = 'f!') def restart_program(): """Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function.""" python = sys.executable os.execl(python, python, * sys.argv) @client.event async def on_ready(): ready_message = "Logged in as" + client.user.name + "\n ID:" + client.user.id print(ready_message)
from osuapi import OsuApi, ReqConnector from flaskext.markdown import Markdown from functools import wraps import binascii import requests import logging import random import redis import json import math import os app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY") md = Markdown(app) #for a markdown work, e.g FAQ osu_api = OsuApi(os.environ.get("osu"), connector=ReqConnector()) Redis = os.environ.get('Redis') OAUTH2_CLIENT_ID = os.environ.get('OAUTH2_CLIENT_ID') OAUTH2_CLIENT_SECRET = os.environ.get('OAUTH2_CLIENT_SECRET') OAUTH2_REDIRECT_URI = os.environ.get('OAUTH2_REDIRECT_URI', 'http://localhost:5000/confirm_login') API_BASE_URL = os.environ.get('API_BASE_URL', 'https://discordapp.com/api') AUTHORIZATION_BASE_URL = API_BASE_URL + '/oauth2/authorize' AVATAR_BASE_URL = "https://cdn.discordapp.com/avatars/" ICON_BASE_URL = "https://cdn.discordapp.com/icons/" DEFAULT_AVATAR = "https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png" DOMAIN = os.environ.get('VIRTUAL_HOST', 'localhost:5000') TOKEN_URL = API_BASE_URL + '/oauth2/token' os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' headers = {"Authorization": os.environ.get("NUREVAM_TOKEN")}
class OsuTracker(commands.Cog): def __init__(self, bot): self.bot = bot self.config = confparser.get("config.json") self.api = OsuApi(key=self.config.osu_token, connector=ReqConnector()) self.last_check_datetime = datetime.datetime.utcnow() self.tracking_channel = None self.tracked_users = self.get_tracked_users() self.tracker_task_loop.start() def cog_unload(self): self.tracker_task_loop.cancel() @tasks.loop(seconds=30) async def tracker_task_loop(self): for user in self.tracked_users: scores = self.api.get_user_best(user['name'], limit=20) for s in [s for s in scores if s.date > self.last_check_datetime]: bmap = self.api.get_beatmaps(beatmap_id=s.beatmap_id)[0] msg = f"{user['nick']} abım {bmap.title} - {bmap.version} mapınde {int(round(s.pp))} pp play yapmıs\n" \ f"helal abım <@{user['discord'].id}>\n".lower().replace('i', 'ı') await self.tracking_channel.send(msg) self.last_check_datetime = datetime.datetime.utcnow() def get_tracked_users(self): with open("tracked_users.json", "r") as f: data = json.load(f) if not json.load(f) == {} else None users = [] if data: for u in data['users']: users.append({ "name": u['name'], "discord": self.bot.get_user(id=u['discord_id']), "nick": u['nick'] }) return users def add_to_tracked_users_file(self, osu_username, discord_id, nick): with open("tracked_users.json", "w") as f: data = json.load(f) if data == {}: data = { "users": [{ "name": osu_username, "discord_id": discord_id, "nick": nick }] } else: data['users'].append({ "name": osu_username, "discord_id": discord_id, "nick": nick }) data.update() print(data) json.dump(data, f) @commands.command() @commands.check(permissions.is_owner) async def osutrack(self, ctx, mem: discord.Member, osu_username, nick): if osu_username not in [u['name'] for u in self.tracked_users]: try: osu_id = self.api.get_user(osu_username)[0].user_id self.tracked_users.append({ "name": osu_username, "nick": nick, "discord": mem }) self.add_to_tracked_users_file(osu_username, discord_id=mem.id, nick=nick) await ctx.send( f"tracking started : {str(mem)}, osu id : {osu_id}") except: await ctx.send(f"couldn't start tracking") else: await ctx.send(f"already tracking : {str(mem)}") @commands.command() @commands.check(permissions.is_owner) async def setch(self, ctx): self.tracking_channel = ctx await ctx.send(f"ok")
embed.set_thumbnail(url=thumbnail) await channel.send(embed=embed) else: return await message.add_reaction('✅') logging.basicConfig(level=logging.INFO) with open('config.toml', 'r') as f: config = toml.load(f) session = aiohttp.ClientSession() osu_api = OsuApi(config['api_keys']['osu'], connector=AHConnector()) tracker = Tracker() async def main(): await add_users_to_tracker() client = MyClient() try: await client.start(config['api_keys']['discord']) except KeyboardInterrupt: pass finally: await client.close() await session.close()
def __init__(self, bot): self.bot = bot self.redis = bot.db.redis self.api = OsuApi(utils.secret["osu"], connector=AHConnector())
def __init__(self, client): self.client = client self.database = self.client.database self.api = OsuApi(self.database.get_osu_api_key(), connector=ReqConnector())
class OsuModule: def __init__(self, client): self.client = client self.database = self.client.database self.api = OsuApi(self.database.get_osu_api_key(), connector=ReqConnector()) # Completed with Rich embed. @commands.command(name='osu') async def osu(self, ctx, *params, member: discord.Member = None): if member is None and len(params) == 0: discord_id = ctx.message.author.id self.database.cursor.execute( "SELECT `osu_id` FROM `users` WHERE `discord_id` = ?", (discord_id, )) osu_id = self.database.cursor.fetchone()[0] embed = self.display_profile(osu_id) await ctx.send(embed=embed) elif len(params) > 0: for osu_id in params: embed = self.display_profile(osu_id) await ctx.send(embed=embed) if member is not None: print(member.id) self.database.cursor.execute( "SELECT `osu_id` FROM `users` WHERE `discord_id` = ?", (member.id, )) osu_id = self.database.cursor.fetchone()[0] embed = self.display_profile(osu_id) await ctx.send(embed=embed) @commands.command(name='top') async def top(self, ctx, *params): (user, amt) = self.params_seperator(ctx, *params) embed = self.top_scores(user, amt) await ctx.send(embed=embed) @commands.command(name='recent') # Completed With Rich Embed. async def recent(self, ctx, *params): (user, amt) = self.params_seperator(ctx, *params) embed = self.recent_scores(user, amt) await ctx.send(embed=embed) @commands.command(name='set') async def set(self, ctx, param): discord_id = ctx.message.author.id osu_id = self.api.get_user(param)[0].user_id self.database.cursor.execute( "SELECT `osu_id` FROM `users` WHERE `discord_id` = ?", (discord_id, )) data = self.database.cursor.fetchone() if data is None: self.database.cursor.execute( "INSERT INTO `users`(`discord_id`, `osu_id`, `days`, `total`) VALUES (?, ?, 0, 0)", (discord_id, osu_id)) self.database.db.commit() title = 'Succesfully set {} IGN as {}'.format( ctx.message.author, param) embed = discord.Embed(title=title, colour=0xDEADBF) await ctx.send(embed=embed) else: await ctx.send("Record Already Exists") @commands.command(name='compare') async def compare(self, ctx, user1, user2): embed = self.check(user1, user2) await ctx.send(embed=embed) @commands.command(name='topr') async def topr(self, ctx, *params): (user, amt) = self.params_seperator(ctx, *params) embed = self.recent_top(user, amt) await ctx.send(embed=embed) def display_profile(self, param): # Obtaining Profile from Paramerter. profile = self.api.get_user(param) # Local Stuff title = "osu! Profile for " + profile[0].username thumbnail = "https://a.ppy.sh/" + str(profile[0].user_id) user_url = "https://osu.ppy.sh/users/" + str(profile[0].user_id) # Embed Creation. embed = discord.Embed(title=title, timestamp=datetime.utcnow(), url=user_url, color=0xFF0418, footer="Osu India bot v.1.0") # thumbnails embed.set_thumbnail(url=thumbnail) # PP embed.add_field(name="PP", value=str(profile[0].pp_raw), inline=True) # Rank embed.add_field(name="Rank", value='#' + str(profile[0].pp_rank), inline=True) # Playcount embed.add_field(name="Playcount", value=str(profile[0].playcount), inline=True) # Accuracy embed.add_field(name="Accuracy", value=str(profile[0].accuracy)[:6], inline=True) # Country Indentification. embed.add_field(name="Country", value=str(profile[0].country), inline=True) # Country Rank. embed.add_field(name="Country Rank", value='#' + str(profile[0].pp_country_rank), inline=True) return embed def top_scores(self, user, amt): # Api Call scores = self.api.get_user_best(user, limit=amt) # Local Stuff. title = "Top {} Scores for {}".format(amt, user) count = 1 # Embed embed = discord.Embed(title=title, timestamp=datetime.utcnow(), color=0xFF0418, footer="Osu India bot v.1.0") # Fields. for score in scores: beatmap = self.api.get_beatmaps(beatmap_id=score.beatmap_id) Title = "#{}. {}[{}] +**{}**".format(count, beatmap[0].title, beatmap[0].version, score.enabled_mods) Value = "PP:{}\n Played {}".format( score.pp, self.time_elapsed(str(score.date))) embed.add_field(name=Title, value=Value, inline=False) count += 1 return embed def recent_scores(self, user, amt): scores = self.api.get_user_recent(user, limit=amt) title = "Recent {} scores for {}".format(amt, user) count = 1 # Discord Embed Creation. embed = discord.Embed(title=title, timestamp=datetime.utcnow(), color=0xFF0418, footer="Osu India bot v0.2.0") # Looping over all Scores and adding fields. for score in scores: beatmap = self.api.get_beatmaps(beatmap_id=score.beatmap_id) name = "#{}. {}[{}] +**{}**".format(count, beatmap[0].title, beatmap[0].version, score.enabled_mods) time_delta = str(score.date) value = "*Played {}\n SR: {}".format( self.time_elapsed(time_delta), str(beatmap[0].difficultyrating)[:5]) embed.add_field(name=name, value=value, inline=False) count += 1 return embed # Hacked this together using 3 lists, modifications needed def recent_top(self, user, amt): scores_list = [] scores = self.api.get_user_best(user, limit=100) for i in range(100): scores_list.append((i + 1, scores[i])) # sort according to date scores_sorted = sorted(scores_list, key=lambda score: score[1].date, reverse=True) title = "Recent {} top scores for {}".format(amt, user) count = 1 # Embed embed = discord.Embed(title=title, timestamp=datetime.utcnow(), color=0xFF0418, footer="Osu India bot v0.2.0") # Fields. for score in scores_sorted: if count > amt: break beatmap = self.api.get_beatmaps(beatmap_id=score[1].beatmap_id) name = "#{}. {}[{}] +**{}**".format(score[0], beatmap[0].title, beatmap[0].version, score[1].enabled_mods) value = "PP:{}\n Played {}".format( score[1].pp, self.time_elapsed(str(score[1].date))) embed.add_field(name=name, value=value, inline=False) count += 1 return embed def check(self, user1, user2): # major formatting required # to add avatar pic no clue how to p1 = self.api.get_user(user1) p2 = self.api.get_user(user2) title = "Comparing stats for " + user1 + " and " + user2 desc = "\t\t" + user1 + " | " + user2 + "\t\t\n" # \t or multiple spaces not working desc += "**Rank :**\t " + str(p1[0].pp_rank) + " | " + str( p2[0].pp_rank) + "\n" desc += "**Country Rank :**\t " + str( p1[0].pp_country_rank) + " | " + str( p2[0].pp_country_rank) + "\n" desc += "**PP :**\t " + str(p1[0].pp_raw) + " | " + str( p2[0].pp_raw) + "\n" desc += "**Accuracy :**\t " + str(p1[0].accuracy)[:5] + " | " + str( p2[0].accuracy)[:5] + "\n" score1 = self.api.get_user_best(user1, limit=1) score2 = self.api.get_user_best(user2, limit=1) desc += "**Top Play :**\t " + str(score1[0].pp) + " | " + str( score2[0].pp) + "\n" desc += "**Playcount :**\t " + str(p1[0].playcount) + " | " + str( p2[0].playcount) + "\n" embed = discord.Embed(title=title, description=desc, colour=0xDEADBF) return embed def time_elapsed(self, datestr): parsed_date = datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S") today = datetime.utcnow() time_delta = relativedelta(today, parsed_date) years = abs(time_delta.years) months = abs(time_delta.months) days = abs(time_delta.days) hours = abs(time_delta.hours) minutes = abs(time_delta.minutes) seconds = abs(time_delta.seconds) time_elapsed = "" if (years > 0): time_elapsed += "{} year{}, ".format(years, "s" if years != 1 else "") if (months > 0): time_elapsed += "{} month{}, ".format(months, "s" if months != 1 else "") if (days > 0): time_elapsed += "{} day{}, ".format(days, "s" if days != 1 else "") if (hours > 0): time_elapsed += "{} hour{}, ".format(hours, "s" if hours != 1 else "") if (minutes > 0): time_elapsed += "{} minute{}, ".format(minutes, "s" if minutes != 1 else "") if (seconds > 0): time_elapsed += "{} second{} ago".format( seconds, "s" if seconds != 1 else "") return time_elapsed def params_seperator(self, ctx, *params): # Default user AND default amount if len(params) == 0: self.database.cursor.execute( "SELECT `osu_id` FROM `users` WHERE `discord_id` = ?", (ctx.message.author.id, )) osu_id = self.database.cursor.fetchone()[0] if osu_id is None: return (None, None) user = self.api.get_user(osu_id)[0].username amt = 5 # Only default amount elif len(params) == 1: user = self.tag_to_id(ctx) if user is False: return (None, None) if user is None: user = params[0] amt = 5 # No defaults else: user = self.tag_to_id(ctx) if user is False: return (None, None) if user is None: user = params[0] amt = params[1] return (user, amt) def tag_to_id(self, ctx): user_list = ctx.message.mentions if len(user_list) == 0: return None else: user_id = user_list[0].id self.database.cursor.execute( "SELECT `osu_id` FROM `users` WHERE `discord_id` = ?", (user_id, )) osu_id = self.database.cursor.fetchone()[0] if osu_id is None: return False return self.api.get_user(osu_id)[0].username def new_recent(self, user_id): scores = self.api.get_user_best(user_id, limit=50) new_scores = [] last_checked = datetime.now( ) # need to save the last checked to a file scores_sorted = sorted(scores, key=lambda s: s.date, reverse=True) # sort according to date for score in scores_sorted: if score.date > last_checked: new_scores.append(score) else: break print("New Recent was executed") return new_scores
from oauth2client.service_account import ServiceAccountCredentials from pprint import pprint from osuapi import OsuApi, ReqConnector from PIL import Image, ImageFont, ImageDraw from datetime import datetime, timezone from discord.ext import commands, tasks import credentials claim_reset_time = 1615139154 TestKey = credentials.TestKey liveKey = credentials.liveKey # osu api key osuapi = OsuApi(credentials.osu, connector=ReqConnector()) # Google api scope scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive'] # Google api credentials creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope) # Google sheets client client = gspread.authorize(creds) # Get the different sheets spreadsheet = client.open("OsuTowerDB") p_sheet = spreadsheet.get_worksheet(0) c_sheet = spreadsheet.get_worksheet(1)
# coll.find_one() # coll.find().count() # coll.save({'test': 1}) # coll.find_one() # coll.find().count() # coll.update({'test': 1}, {'test': 2}) # coll.find_one() # coll.find().count() if __name__ == '__main__': apikey = # your Osu! API key user_ids = random.sample(range(1, 5000000), 500000) api = OsuApi(apikey, connector=AHConnector()) collected = 0 i = 0 requests = 0 while requests < 550000: user_id = user_ids[i] try: results = asyncio.get_event_loop().run_until_complete(get_user_recent(api, user_id)) requests += 1 time.sleep(0.25) if results != []: for result in results: user_recent.save(parse_user_recent(result, user_id)) collected = collected + 1 ''' else:
import requests from osuapi import OsuApi, ReqConnector import json api = OsuApi("f0bfd051b9e0dba2d56b96a71b416061593d7f31", connector=ReqConnector()) user = "******" scoreThreshold = 5000000000 results = api.get_user_recent(user, limit=1) recentScore = results[0] beatmaps = api.get_beatmaps(beatmap_id=recentScore.beatmap_id, limit=1) beatmapData = beatmaps[0] debugMessage = "User {} ({}) got a score of {} and rank {} on beatmap {} (#{}) at {}" print( debugMessage.format(user, recentScore.user_id, recentScore.score, recentScore.rank, beatmapData.title, recentScore.beatmap_id, recentScore.date))
import aiohttp import os from osuapi import OsuApi, AHConnector osu_api = OsuApi(os.getenv("osu_token"), connector=AHConnector()) class Api: requests = 0 @staticmethod async def get_user(username): try: get_user = await osu_api.get_user(username) Api.requests += 1 return get_user[0] except IndexError: return @staticmethod async def get_user_recent(user_id, limit=0, lslist=False): try: get_user_recent = await osu_api.get_user_recent(user_id, limit=limit + 1) Api.requests += 1 return get_user_recent[limit if lslist is False else None] except IndexError: return except TypeError:
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from osuapi import OsuApi, ReqConnector import requests from pprint import pprint # Easy way to test card designs osuapi = OsuApi("your key", connector=ReqConnector()) rank = "C" def create_card(map_id=131891): raw = "Hidden spunout nofail" score_mods = raw.split(" ") card_name = f"{map_id}{discord_id}" map_object = osuapi.get_beatmaps(mode=0, beatmap_id=map_id, limit=30)[0] response = requests.get(f"https://assets.ppy.sh/beatmaps/{map_object.beatmapset_id}/covers/cover.jpg") pprint("Grabbed map image") file = open(f"cards/{card_name}.png", "wb") file.write(response.content) file.close() img = Image.open(f"cards/{card_name}.png") img2 = Image.open(f"bace/cardbace{rank}.png") img2.paste(img, (15,55)) draw = ImageDraw.Draw(img2) font = ImageFont.truetype("font/Exo2.0-Regular.otf", 24) combo_font = ImageFont.truetype("font/Overpass-Regular.ttf", 70) Score_font = ImageFont.truetype("font/Overpass-Regular.ttf", 60)
data_info.OAUTH2_CLIENT_ID = secret['OAUTH2_CLIENT_ID'] data_info.OAUTH2_CLIENT_SECRET = secret['OAUTH2_CLIENT_SECRET'] data_info.OAUTH2_REDIRECT_URI = secret.get('OAUTH2_REDIRECT_URI', 'http://localhost:5000/confirm_login') data_info.API_BASE_URL = 'https://discordapp.com/api' data_info.AUTHORIZATION_BASE_URL = data_info.API_BASE_URL + '/oauth2/authorize' data_info.AVATAR_BASE_URL = "https://cdn.discordapp.com/avatars/" data_info.ICON_BASE_URL = "https://cdn.discordapp.com/icons/" data_info.DEFAULT_AVATAR = "https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png" data_info.DOMAIN = secret.get('VIRTUAL_HOST', 'localhost:5000') data_info.TOKEN_URL = data_info.API_BASE_URL + '/oauth2/token' os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' data_info.headers = {"Authorization": "Bot " + secret["nurevam_token"]} data_info.anilist_token = secret["anilist_token"] data_info.anilist_id = secret["anilist_id"] utils.data_info = data_info osu_api = OsuApi(secret["osu"], connector=ReqConnector()) files_cogs = db.smembers("Website:Cogs") blueprint_lib = {} data_info.last_path = None #getting last path so we can redirect it easily after login. #loading cogs within dirty way, so I can test other files without need to edit this (when push to server) for x in files_cogs: lib = importlib.import_module("cogs.{}".format(x)) blueprint_lib[x] = lib app.register_blueprint(lib.blueprint, url_prefix="/"+x) lib.db = app.db app.blueprint_lib = blueprint_lib log.info("Loading done, {}".format(blueprint_lib.keys())) lib = importlib.import_module("non-cogs.profile")
import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') import datetime from datetime import date from pyecharts import options as opts from pyecharts.charts import Bar, Page, Pie, Grid from pyecharts.faker import Collector, Faker from pyecharts.globals import ThemeType from pyecharts.components import Table, Image from pyecharts.options import ComponentTitleOpts from pyecharts.commons.utils import JsCode from osuapi import OsuApi, ReqConnector, OsuMode import requests api = OsuApi("13a36d70fd32e2f87fd2a7a89e4f52d54ab337a1", connector=ReqConnector()) user_name = input('Please enter osu! user name:') ####################### get mapper beatmaps info ####################### try: beatmap_list= api.get_beatmaps(since=None, beatmapset_id=None, beatmap_id=None, username=user_name, mode=None, include_converted=True, beatmap_hash=None, limit=500) df_beatmap = pd.DataFrame() for beatmap in beatmap_list: df_beatmap_1 = pd.DataFrame( dict(beatmap), index=[0]) df_beatmap = df_beatmap.append(df_beatmap_1, ignore_index=True) except: print('No results for user name') sys.exit()
class Osu(commands.Cog): def __init__(self, discordClient): with open("config.json") as f: config = json.loads(f.read()) self.bot = discordClient self.osuApi = OsuApi(config["osu_key"], connector=ReqConnector()) self.modeMap = {'standard': enums.OsuMode.osu, 'mania': enums.OsuMode.mania} self.db = 'guild_settings.db' self.table = 'settings' self.settings = {'guild_id': 'guild_id', 'guild_name': 'guild_name', 'commands_disabled': 'commands_disabled', 'roll_channel': 'roll_channel', 'osu_channel': 'osu_channel', 'admin_role': 'admin_role'} def check_correct_channel(self, message): conn = sqlite3.connect(self.db) c = conn.cursor() with conn: c.execute("SELECT {} FROM {} WHERE guild_id=?".format(self.settings['osu_channel'], self.table), (message.guild.id,)) channel = c.fetchone() conn.close() return(not channel[0] == message.channel.name) @commands.group() async def osu(self, ctx): if ctx.invoked_subcommand is None: return(await ctx.send('Invalid subcommand for osu passed...')) @osu.command() async def profile(self, ctx, profile, mode_arg="standard"): if self.check_correct_channel(ctx.message): return(await ctx.send('You cannot use this command in this channel')) if mode_arg not in self.modeMap: return(await ctx.send('Not a valid game mode')) else: result = self.osuApi.get_user(str(profile),mode=self.modeMap[mode_arg], event_days=31) if not result: return(await ctx.send("User doesn't exist")) data = result[0] #get first and only result acc = str(math.ceil(data.accuracy*100)/100) + "%" lvl = str(math.ceil(data.level*100)/100) profile_embed = discord.Embed( url = "https://osu.ppy.sh/users/{}".format(data.user_id), color = 0xea1595 ) profile_embed.add_field( name = "Performance", value = "Global PP Rank: {0}\nPP: {1}\nAccuracy: {2}".format(data.pp_rank, data.pp_raw, acc), inline = True ) profile_embed.add_field( name = "Experience", value = "Playcount: {0}\nLevel: {1}\n".format(data.playcount, lvl), inline = True ) profile_embed.add_field( name = "Country", value = emoji.emojize("Country PP Rank: {0}\n:flag_{1}:" .format(data.pp_country_rank, data.country.lower()) ), inline = True ) profile_embed.set_author( name = data.username, url = "https://osu.ppy.sh/users/{}".format(data.user_id), icon_url = "http://s.ppy.sh/a/{}".format(data.user_id) ) return(await ctx.send(embed=profile_embed)) @osu.command() async def best(self, ctx, username, mode_arg="standard"): if self.check_correct_channel(ctx.message): return(await ctx.send('You cannot use this command in this channel')) if mode_arg not in self.modeMap: return(await ctx.send('Not a valid game mode')) else: result = self.osuApi.get_user_best(username,mode=self.modeMap[mode_arg], limit=1) if not result: return(await ctx.send("User doesn't exist")) data = result[0] #get first and only result best_embed = discord.Embed( url = "https://osu.ppy.sh/users/{}".format(data.user_id), color = 0xea1595 ) best_embed.add_field( name="Score", value="Score: {0}\nMax Combo: {1}\nPerfect: {2}".format(data.score, data.maxcombo, data.perfect), inline = True ) best_embed.add_field( name="Count", value="Count50: {0}\nCount100: {1}\nCount300: {2}\nMisses: {3}".format(data.count50, data.count100, data.count300, data.countmiss), inline=True ) best_embed.set_author( name = username, url = "https://osu.ppy.sh/users/{}".format(data.user_id), icon_url = "http://s.ppy.sh/a/{}".format(data.user_id) ) return(await ctx.send(embed=best_embed)) @best.error @profile.error async def error(self, ctx, error): return(await ctx.send(str(error).capitalize()))
from os import name from SwSpotify import SpotifyClosed, SpotifyNotRunning, spotify import SwSpotify from osuapi import OsuApi, ReqConnector import requests import json import obswebsocket, obswebsocket.requests, obswebsocket.events from threading import Thread import launchpad_py from websockets import server from radke_logging import Logger, loggingLevel import keyboard from time import sleep import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) api = OsuApi("346ab1522e56b657ada35ff7075f3553ee3fac24", connector=ReqConnector()) lp = launchpad_py.Launchpad() obs = obswebsocket.obsws() logger = Logger(True, "espdeck.log", 3) launchpadEnabled = False websocketEnabled = False if (lp.Check(0)): launchpadEnabled = True lp.Open(0) lp.LedCtrlXY(6, 8, 0, 3) lp.LedCtrlXY(7, 8, 3, 0) lp.LedCtrlXY(8, 8, 3, 0) lp.LedCtrlXY(5, 6, 0, 3) lp.LedCtrlXY(6, 6, 2, 3) lp.LedCtrlXY(7, 6, 0, 3) lp.LedCtrlXY(4, 8, 3, 0)
from osuapi import OsuApi, ReqConnector import requests import json import sqlite3 import datetime with open("apicode.json") as apc: apicode = json.load(apc)[0]["apicode"] api = OsuApi(apicode, connector = ReqConnector()) playername = "potla" user = api.get_user(playername) def compare_maps(a, b): affinity = 0 ID1 = a.split(" ")[0] ID2 = b.split(" ")[0] if ID1 != ID2: return 0 if "NoMod" in a and "NoMod" in b: return 2 if "Hidden" in a and "Hidden" in b: affinity += 1 if "HardRock" in a and "HardRock" in b: affinity += 1 if "DoubleTime" in a or "Nightcore" in a and "DoubleTime" in b or "Nightcore" in b: affinity += 1 return affinity def mod_finder(score, counter): ID = score.split(" ")[0]
def __init__(self, bot): self.api = OsuApi(config.osu, connector=AHConnector()) self.bot = bot
import re import pyoppai import constants import recommendation import update_stats from datetime import datetime import requests from osuapi import OsuMode, BeatmapStatus, OsuApi, ReqConnector from userlink_key import userlink client = commands.Bot(command_prefix=commands.when_mentioned_or( constants.Settings.commandPrefix)) client.remove_command("help") commandPrefix = constants.Settings.commandPrefix api = OsuApi(constants.Api.osuApiKey, connector=ReqConnector()) LogFile = open(constants.Paths.logsFile, "a") mainChannel = None logsChannel = None botOwner = None Refresh = True databasePath = constants.Paths.beatmapDatabase conn = sqlite3.connect(constants.Paths.beatmapDatabase) cursor = conn.cursor() userlink = userlink(conn) def return_user_rank(discordId):
from osuapi import OsuApi, ReqConnector, enums import aiohttp, asyncio, sys, os, datetime, pprint, shelve from threading import Lock import OSDLBot_storage api = OsuApi(os.environ.get('OSU_API_KEY'), connector=ReqConnector()) lock = Lock() class MatchNotFoundError(Exception): pass class PlayerNotFound(Exception): pass class Map(): def __init__(self, map_id): self.map = api.get_beatmaps(beatmap_id=map_id)[0] self.id = self.map.beatmap_id self.title = self.map.title class Game(): def __init__(self, game_api): self.is_v2 = game_api.scoring_type == enums.ScoringType.score_v2 self.map = Map(game_api.beatmap_id) self.mods = game_api.mods #init player scores dict {Player: score} self.player_scores = {}
class Osu: def __init__(self, bot): self.bot = bot if bot.config['osu']: self.api = OsuApi(bot.config['osu'], connector=AHConnector()) else: self.api = None @classmethod def osu_mode_converter(self, mode=None): if mode is 0 or 'standard' or 'osu!standard' or 'osu!' or None: return osuapi.enums.OsuMode.osu elif mode is 1 or 'ctb' or 'catchthebeat' or 'osu!catch' or 'catch': return osuapi.enums.OsuMode.catch elif mode is 2 or 'taiko' or 'osu!taiko': return osuapi.enums.OsuMode.taiko elif mode is 3 or 'mania' or 'osu!mania': return osuapi.enums.OsuMode.mania else: return 'Unknown' def __unload(self): logging.info('osu[api]: Closing session.') try: self.api.close() except Exception: logging.error('osu[api]: Wow, amazing! ' 'You closed the instance early. GJ.') else: logging.info('osu[unload]: OK') @commands.group() async def osu(self, ctx): """Commands for osu!""" if ctx.invoked_subcommand is None: help_em = discord.Embed(title='Commands for osu!', colour=0x690E8) help_em.add_field(name='user', value='Gets info on osu! players.' ' `^osu user *user*`') await ctx.send(embed=help_em) @osu.command() async def user(self, ctx, u: str, mode=None): """Returns information on a osu! player. If the player name you are searching has spaces, use quotation marks. e.g. ^osu user "player name with spaces" Special thanks to khazhyk for the library this command uses. By default this command defaults to osu!standard. All modes are supported. To use osu!standard, leave mode blank, or use 'standard', 'osu!standard', 'osu!' or 0. To use osu!catch, use 'catch', 'osu!catch', or 1. To use osu!taiko, use 'taiko', 'osu!taiko', or 2. To use osu!mania, use 'mania', 'osu!mania', or 3. Any other modes will return 'Unknown' error. (Service error) """ if self.api: mode = self.osu_mode_converter(mode=mode) if mode == 'Unknown': raise utils.errors.ServiceError('Unknown mode') user = await self.api.get_user(u, mode=mode) try: user = user[0] pp = user.pp_raw # CHAR SAVING. ss = user.count_rank_ss s = user.count_rank_s a = user.count_rank_a except IndexError: return await ctx.send('User does not exist, ' 'maybe try one that does') else: raise utils.errors.ServiceError('osu! api key not configured') osu_embed = discord.Embed(title=f'osu! stats', colour=0x690E8) osu_embed.set_author(name=f'{u} ({user.country}' f' #{user.pp_country_rank}, global' f' #{user.pp_rank})', icon_url='https://osu.ppy.sh/images/flags/' f'{user.country}.png') osu_embed.set_thumbnail(url=f'https://a.ppy.sh/{user.user_id}') osu_embed.add_field(name='Hits (300/100/50)', value=f'{user.count300}/' f'{user.count100}/' f'{user.count50}') osu_embed.add_field(name='Play count', value=user.playcount) osu_embed.add_field(name='Ranked score', value=user.ranked_score) osu_embed.add_field(name='Total score', value=user.total_score) osu_embed.add_field(name='Level', value=int(user.level)) osu_embed.add_field(name='Total PP', value=f'{round(pp, 2)} PP') osu_embed.add_field(name='Accuracy', value=f'{user.accuracy:.1f}%') osu_embed.add_field(name='Plays (SS/S/A)', value=f'{ss}/{s}/{a}') await ctx.send(embed=osu_embed)