def background_check_feed(feed): logger.info(feed + ': Starting up background_check_feed') yield from client.wait_until_ready() # make sure debug output has this check run in the right order... yield from asyncio.sleep(1) FEED = config[feed] feed_url = FEED.get('feed_url') rss_refresh_time = FEED.getint('rss_refresh_time', 3600) max_age = FEED.getint('max_age', 86400) channels = [] for key in FEED.get('channels').split(','): logger.debug(feed + ': adding channel ' + key) channels.append(discord.Object(id=config['CHANNELS'][key])) while not client.is_closed: try: logger.info(feed + ': processing feed') if FEED.getint('send_typing', 0) >= 1: for channel in channels: try: yield from client.send_typing(channel) except discord.errors.Forbidden: logger.error(feed + ':discord.errors.Forbidden') logger.error(sys.exc_info()) logger.error( feed + ":Perhaps bot isn't allowed in one this channel?") logger.error(channel) http_headers = {} http_headers['User-Agent'] = MAIN.get('UserAgent', 'feed2discord/1.0') ### Download the actual feed, if changed since last fetch cursor = conn.cursor() cursor.execute( "select lastmodified,etag from feed_info where feed=? OR url=?", [feed, feed_url]) data = cursor.fetchone() if data is None: logger.info(feed + ':looks like updated version. saving info') cursor.execute( "REPLACE INTO feed_info (feed,url) VALUES (?,?)", [feed, feed_url]) conn.commit() logger.debug(feed + ':feed info saved') else: logger.debug(feed + ':setting up extra headers for HTTP request.') logger.debug(data) lastmodified = data[0] etag = data[1] if lastmodified is not None and len(lastmodified): logger.debug(feed + ':adding header If-Modified-Since: ' + lastmodified) http_headers['If-Modified-Since'] = lastmodified else: logger.debug(feed + ':no stored lastmodified') if etag is not None and len(etag): logger.debug(feed + ':adding header ETag: ' + etag) http_headers['ETag'] = etag else: logger.debug(feed + ':no stored ETag') logger.debug(feed + ':sending http request for ' + feed_url) http_response = yield from httpclient.request('GET', feed_url, headers=http_headers) logger.debug(http_response) if http_response.status == 304: logger.debug(feed + ':data is old; moving on') http_response.close() raise HTTPNotModified() elif http_response.status != 200: logger.debug(feed + ':HTTP error: ' + http_response.status) http_response.close() raise HTTPError() else: logger.debug(feed + ':HTTP success') logger.debug(feed + ':reading http response') http_data = yield from http_response.read() logger.debug(feed + ':parsing http data') feed_data = feedparser.parse(http_data) logger.debug(feed + ':done fetching') if 'ETAG' in http_response.headers: etag = http_response.headers['ETAG'] logger.debug(feed + ':saving etag: ' + etag) cursor.execute( "UPDATE feed_info SET etag=? where feed=? or url=?", [etag, feed, feed_url]) conn.commit() logger.debug(feed + ':etag saved') else: logger.debug(feed + ':no etag') if 'LAST-MODIFIED' in http_response.headers: modified = http_response.headers['LAST-MODIFIED'] logger.debug(feed + ':saving lastmodified: ' + modified) cursor.execute( "UPDATE feed_info SET lastmodified=? where feed=? or url=?", [modified, feed, feed_url]) conn.commit() logger.debug(feed + ':saved lastmodified') else: logger.debug(feed + ':no last modified date') http_response.close() logger.debug(feed + ':processing entries') for item in feed_data.entries: logger.debug(feed + ':item:processing this entry') # logger.debug(item) # can be very noisy id = '' if 'id' in item: id = item.id elif 'guid' in item: id = item.guid else: logger.error(feed + ':item:no id, skipping') continue pubDateDict = extract_best_item_date(item) pubDate = pubDateDict['date'] pubDate_parsed = pubDateDict['date_parsed'] logger.debug(feed + ':item:id:' + id) logger.debug(feed + ':item:checking database history for this item') cursor.execute( "SELECT published,title,url,reposted FROM feed_items WHERE id=?", [id]) data = cursor.fetchone() if data is None: logger.info(feed + ':item ' + id + ' unseen, processing:') cursor.execute( "INSERT INTO feed_items (id,published) VALUES (?,?)", [id, pubDate]) conn.commit() if time.mktime(pubDate_parsed) > (time.time() - max_age): logger.info(feed + ':item:fresh and ready for parsing') logger.debug(feed + ':item:building message') message = build_message(FEED, item) for channel in channels: logger.debug(feed + ':item:sending message') yield from client.send_message(channel, message) else: logger.info(feed + ':too old; skipping') logger.debug(feed + ':now:' + str(time.time())) logger.debug(feed + ':now:gmtime:' + str(time.gmtime())) logger.debug(feed + ':now:localtime:' + str(time.localtime())) logger.debug(feed + ':pubDate:' + str(pubDate)) logger.debug(feed + ':pubDate_parsed:' + str(pubDate_parsed)) if debug >= 4: logger.debug(item) else: logger.debug(feed + ':item:' + id + ' seen before, skipping') except HTTPNotModified: logger.debug( feed + ':Headers indicate feed unchanged since last time fetched:') logger.debug(sys.exc_info()) except HTTPError: logger.warn(feed + ':Unexpected HTTP error:') logger.warn(sys.exc_info()) logger.warn(feed + ':Assuming error is transient and trying again later') except sqlite3.Error as sqlerr: logger.error(feed + ':sqlite3 error: ') logger.error(sys.exc_info()) logger.error(sqlerr) raise except discord.errors.Forbidden: logger.error(feed + ':discord.errors.Forbidden') logger.error(sys.exc_info()) logger.error( feed + ":Perhaps bot isn't allowed in one of the channels for this feed?" ) # raise # or not? hmm... except: logger.error(feed + ':Unexpected error:') logger.error(sys.exc_info()) logger.error(feed + ':giving up') raise finally: # No matter what goes wrong, wait same time and try again logger.debug(feed + ':sleeping for ' + str(rss_refresh_time) + ' seconds') yield from asyncio.sleep(rss_refresh_time)
async def start(self, ctx, *, channel=None, wait=False): """|coro| Starts the interactive menu session. Parameters ----------- ctx: :class:`Context` The invocation context to use. channel: :class:`discord.abc.Messageable` The messageable to send the message to. If not given then it defaults to the channel in the context. wait: :class:`bool` Whether to wait until the menu is completed before returning back to the caller. Raises ------- MenuError An error happened when verifying permissions. discord.HTTPException Adding a reaction failed. """ # Clear the buttons cache and re-compute if possible. try: del self.buttons except AttributeError: pass self.bot = bot = ctx.bot self.ctx = ctx self._author_id = ctx.author.id channel = channel or ctx.channel is_guild = isinstance(channel, discord.abc.GuildChannel) me = channel.guild.me if is_guild else ctx.bot.user permissions = channel.permissions_for(me) self.__me = discord.Object(id=me.id) self._verify_permissions(ctx, channel, permissions) self._event.clear() msg = self.message if msg is None: self.message = msg = await self.send_initial_message(ctx, channel) if self.should_add_reactions(): # Start the task first so we can listen to reactions before doing anything for task in self.__tasks: task.cancel() self.__tasks.clear() self._running = True self.__tasks.append(bot.loop.create_task(self._internal_loop())) async def add_reactions_task(): for emoji in self.buttons: await msg.add_reaction(emoji) self.__tasks.append(bot.loop.create_task(add_reactions_task())) if wait: await self._event.wait()
async def on_ready(): print('Logged in as') print(asuka.client.user.name) print(asuka.client.user.id) print('------') await asuka.client.send_message(discord.Object('496185128171864065'), 'I have returned!')
async def convert(self, ctx: commands.Context, arg: str) -> _RawRole: with contextlib.suppress(commands.BadArgument): return await super().convert(ctx, arg) if match := _id_regex.match(arg) or _mention_regex.match(arg): return discord.Object(int(match.group(1)))
global counter2 global counter3 global weight global weight_time global seconds_elapsed bot_token = 'NjQ4NTUxNjM4Mzc3NjkzMTk1.Xdv40A.nrATZYQLTd3nlKrEO_0zITb7uxg' self_bot_token = 'NTQ5OTQwOTc3MTE3Mjk4NzA4.XSxtxA.p7sDLqU4kCjN240l7r7uCE-xXp0' message = None embed = None embed_best = None #trivia-answers output_channel = discord.Object(id='603475810489466880') input_hq_private = [ "603475810489466880", "593990608914219008", "569420128794443776", "601814968710594627", "595635734904307742", "603556969025896458", "601966175525666817", "590224806256050196", "590182835948879872", "570257859850272788", "590471026899550208", "589120764347678750", "585682137202819101",
async def massban(self, ctx, *, args): """Mass bans multiple members from the server. This command has a powerful "command line" syntax. To use this command you and the bot must both have Ban Members permission. **Every option is optional.** Users are only banned **if and only if** all conditions are met. The following options are valid. `--channel` or `-c`: Channel to search for message history. `--reason` or `-r`: The reason for the ban. `--regex`: Regex that usernames must match. `--created`: Matches users whose accounts were created less than specified minutes ago. `--joined`: Matches users that joined less than specified minutes ago. `--joined-before`: Matches users who joined before the member ID given. `--joined-after`: Matches users who joined after the member ID given. `--no-avatar`: Matches users who have no avatar. (no arguments) `--no-roles`: Matches users that have no role. (no arguments) `--show`: Show members instead of banning them (no arguments). Message history filters (Requires `--channel`): `--contains`: A substring to search for in the message. `--starts`: A substring to search if the message starts with. `--ends`: A substring to search if the message ends with. `--match`: A regex to match the message content to. `--search`: How many messages to search. Default 100. Max 2000. `--after`: Messages must come after this message ID. `--before`: Messages must come before this message ID. `--files`: Checks if the message has attachments (no arguments). `--embeds`: Checks if the message has embeds (no arguments). """ # For some reason there are cases due to caching that ctx.author # can be a User even in a guild only context # Rather than trying to work out the kink with it # Just upgrade the member itself. if not isinstance(ctx.author, discord.Member): try: author = await ctx.guild.fetch_member(ctx.author.id) except discord.HTTPException: return await ctx.send( 'Somehow, Discord does not seem to think you are in this server.' ) else: author = ctx.author parser = Arguments(add_help=False, allow_abbrev=False) parser.add_argument('--channel', '-c') parser.add_argument('--reason', '-r') parser.add_argument('--search', type=int, default=100) parser.add_argument('--regex') parser.add_argument('--no-avatar', action='store_true') parser.add_argument('--no-roles', action='store_true') parser.add_argument('--created', type=int) parser.add_argument('--joined', type=int) parser.add_argument('--joined-before', type=int) parser.add_argument('--joined-after', type=int) parser.add_argument('--contains') parser.add_argument('--starts') parser.add_argument('--ends') parser.add_argument('--match') parser.add_argument('--show', action='store_true') parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds)) parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments)) parser.add_argument('--after', type=int) parser.add_argument('--before', type=int) try: args = parser.parse_args(shlex.split(args)) except Exception as e: return await ctx.send(str(e)) members = [] if args.channel: channel = await commands.TextChannelConverter().convert( ctx, args.channel) before = args.before and discord.Object(id=args.before) after = args.after and discord.Object(id=args.after) predicates = [] if args.contains: predicates.append(lambda m: args.contains in m.content) if args.starts: predicates.append(lambda m: m.content.startswith(args.starts)) if args.ends: predicates.append(lambda m: m.content.endswith(args.ends)) if args.match: try: _match = re.compile(args.match) except re.error as e: return await ctx.send( f'Invalid regex passed to `--match`: {e}') else: predicates.append(lambda m, x=_match: x.match(m.content)) if args.embeds: predicates.append(args.embeds) if args.files: predicates.append(args.files) async for message in channel.history(limit=min( max(1, args.search), 2000), before=before, after=after): if all(p(message) for p in predicates): members.append(message.author) else: members = ctx.guild.members # member filters predicates = [ lambda m: isinstance(m, discord.Member) and can_execute_action( ctx, author, m), # Only if applicable lambda m: not m.bot, # No bots lambda m: m.discriminator != '0000', # No deleted users ] async def _resolve_member(member_id): r = ctx.guild.get_member(member_id) if r is None: try: return await ctx.guild.fetch_member(member_id) except discord.HTTPException as e: raise commands.BadArgument( f'Could not fetch member by ID {member_id}: {e}' ) from None return r if args.regex: try: _regex = re.compile(args.regex) except re.error as e: return await ctx.send(f'Invalid regex passed to `--regex`: {e}' ) else: predicates.append(lambda m, x=_regex: x.match(m.name)) if args.no_avatar: predicates.append(lambda m: m.avatar is None) if args.no_roles: predicates.append(lambda m: len(getattr(m, 'roles', [])) <= 1) now = datetime.datetime.utcnow() if args.created: def created(member, *, offset=now - datetime.timedelta(minutes=args.created)): return member.created_at > offset predicates.append(created) if args.joined: def joined(member, *, offset=now - datetime.timedelta(minutes=args.joined)): if isinstance(member, discord.User): # If the member is a user then they left already return True return member.joined_at and member.joined_at > offset predicates.append(joined) if args.joined_after: _joined_after_member = await _resolve_member(args.joined_after) def joined_after(member, *, _other=_joined_after_member): return member.joined_at and _other.joined_at and member.joined_at > _other.joined_at predicates.append(joined_after) if args.joined_before: _joined_before_member = await _resolve_member(args.joined_before) def joined_before(member, *, _other=_joined_before_member): return member.joined_at and _other.joined_at and member.joined_at < _other.joined_at predicates.append(joined_before) members = {m for m in members if all(p(m) for p in predicates)} if len(members) == 0: return await ctx.send('No members found matching criteria.') if args.show: members = sorted(members, key=lambda m: m.joined_at or now) fmt = "\n".join( f'{m.id}\tJoined: {m.joined_at}\tCreated: {m.created_at}\t{m}' for m in members) content = f'Current Time: {datetime.datetime.utcnow()}\nTotal members: {len(members)}\n{fmt}' file = discord.File(io.BytesIO(content.encode('utf-8')), filename='members.txt') return await ctx.send(file=file) if args.reason is None: return await ctx.send('--reason flag is required.') else: reason = await ActionReason().convert(ctx, args.reason) count = 0 for member in members: try: await ctx.guild.ban(member, reason=reason) except discord.HTTPException: pass else: count += 1 await ctx.send(f'Banned {count}/{len(members)}')
import sys, os import youtube_dl import ffmpeg import time as t import urllib.request import json from discord.ext import commands # 기본 볼륨을 지정해주세요 값은 0.0부터 1.0입니다. defultvolum = 0.2 # (20%) # 자막이 있는 영상만 찾으려면 closedCaption을 자막이 없는영상도 포함하려면 any를 입력해주세요 defultvideoSub = "any" # 채널id와 토큰을 입력해주세요. channel = discord.Object(id='##################') token = "###########################################################" beforeArgs = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5" def ResetBot(): executable = sys.executable args = sys.argv[:] args.insert(0, sys.executable) print("재시작 중...") os.execvp(executable, args) playonoffs = {} queues = {}
async def Tina(): await bot.wait_until_ready() while not bot.is_closed: async with websockets.connect('wss://getdownon.it/storas-relay') as websocket: while True: try: get = await websocket.recv() except: await bot.send_message(discord.Object(id='348621766702268416'), "Websockets died... bot is turning off should be back shortly...") await bot.logout() await bot.close() statsd.increment('Tina.new_score') api = json.loads(get) osu_api = osu.bid(api["beatmap_id"]) if osu_api == None: print("Blame peppy got api error...") else: formatter = { "performance_new": "{}".format(api["new_player"]["performance"]), "personal_top": api["personal_top"], "mode": ConvertMods.convertMode(api["mode"]), "global_rank": api["new_player"]["rank"], "country": api["country"], "country_rank": api["new_player"]["country_rank"], "performance": "{:.2f}".format(api["new_score"]["performance"]), "combo": api["new_score"]["max_combo"], "max_combo": osu_api[0]["max_combo"], "rank": api["new_score"]["rank"], "stars": "{:.2f}".format(float(osu_api[0]["difficultyrating"])), "score": "{:,d}".format(api["new_score"]["score"]), "accuracy": "{:.2f}".format(api["new_score"]["accuracy"]), "mods": ConvertMods.ModsRev(api["new_score"]["mods"]), "artist": osu_api[0]["artist"], "title": osu_api[0]["title"], "version": osu_api[0]["version"], "sid": osu_api[0]["beatmapset_id"], "userid": api["user_id"], "username": api["username"] } new_score = "New score +{performance}pp gain • #{personal_top} personal best\n".format( **formatter) new_score += "Mode {mode} • Global rank #{global_rank} • {country} Country rank #{country_rank} • PP {performance_new}\n".format( **formatter) new_score += "Combo {combo} / {max_combo} • Rank {rank} • Score {score} • Accuracy {accuracy}% • Mods {mods}\n".format( **formatter) new_score += "{artist} - {title} [{version}] {stars}★\n".format(**formatter) if formatter["personal_top"] == 1: e = discord.Embed(title="", url="https://ripple.moe/u/{}".format( api["user_id"]), colour=discord.Colour.gold(), description="{}".format(new_score)) elif formatter["personal_top"] == 2: e = discord.Embed(title="", url="https://ripple.moe/u/{}".format( api["user_id"]), colour=discord.Colour.light_grey(), description="{}".format(new_score)) elif formatter["personal_top"] == 3: e = discord.Embed(title="", url="https://ripple.moe/u/{}".format( api["user_id"]), colour=discord.Colour.dark_orange(), description="{}".format(new_score)) else: e = discord.Embed(title="", url="https://ripple.moe/u/{}".format( api["user_id"]), colour=discord.Colour.darker_grey(), description="{}".format(new_score)) e.set_thumbnail( url="https://b.ppy.sh/thumb/{sid}.jpg".format(**formatter)) e.set_author(name='{username}'.format(**formatter), icon_url="https://a.ripple.moe/{userid}".format(**formatter)) e.set_footer(text="{}".format(strftime("%d.%m.%Y at %H:%M", gmtime()))) if 1 <= formatter["personal_top"] <= 50: await bot.send_message(discord.Object(id='348621766702268416'), embed=e)
async def owner(self, ctx): member = ctx.message.author console = discord.Object('316688736089800715') if member.id not in ownerids: await self.bot.say( ":x: You do not have permission to execute this command.") else: try: args = ctx.message.content args = args.split(' ') if args[1] == "shutdown": await self.bot.say( "I-I'm hurt! Ah well, I never loved you anyway! :broken_heart: :sob:" ) await self.bot.send_message( console, ':warning: [`' + str(datetime.datetime.now().strftime( "%d/%m/%y %H:%M:%S")) + '`] `' + str(ctx.message.author) + '` successfully shutdown Godavaru!') raise SystemExit elif args[1] == "game": gargs = ctx.message.content gargs = gargs.replace( self.bot.command_prefix[0] + "owner game", "") gargs = gargs.replace( self.bot.command_prefix[1] + "owner game", "") server_count = 0 member_count = 0 for server in self.bot.servers: server_count += 1 for member in server.members: member_count += 1 if gargs == "": await self.bot.say( ":x: You must specify a game or `reset`!") elif gargs == " reset": await self.bot.change_presence(game=discord.Game( name='g_help | with ' + str(server_count) + ' servers and ' + str(member_count) + ' users!')) await self.bot.say( ":white_check_mark: Reset my playing status.") else: await self.bot.change_presence(game=discord.Game( name='g_help |' + str(gargs))) await self.bot.say( ":white_check_mark: Set my playing status to `g_help |" + str(gargs) + "`!") elif args[1] == "leaveserver": await self.bot.say( ":white_check_mark: I have left this server. Bye! :wave:" ) await self.bot.leave_server(ctx.message.server) # It's just us now. Just be calm and it shall all be over soon... elif args[1] == "todo": todoChannel = discord.Object('316638257104551946') targs = ctx.message.content targs = targs.replace( self.bot.command_prefix[0] + "owner todo", "") targs = targs.replace( self.bot.command_prefix[1] + "owner todo", "") if targs == "": await self.bot.say( ':x: Couldn\'t add your message to the todo list. Reason: Cannot send an empty message.' ) else: await self.bot.send_message(todoChannel, "-" + str(targs)) await self.bot.say( ':white_check_mark: Successfully added your message to the to-do list!' ) # Va, je ne te hais point. elif args[1] == "nick": nargs = ctx.message.content nargs = nargs.replace( self.bot.command_prefix[0] + "owner nick", "") nargs = nargs.replace( self.bot.command_prefix[1] + "owner nick", "") if nargs == "": await self.bot.say( ":x: You must specify either a nickname or `reset`!" ) elif nargs == " reset": await self.bot.change_nickname(ctx.message.server.me, "") await self.bot.say( ":white_check_mark: My nickname was reset!") else: await self.bot.change_nickname(ctx.message.server.me, str(nargs)) await self.bot.say( ":white_check_mark: My nickname was changed to `" + str(nargs) + "` successfully!") elif args[1] == "status": sargs = ctx.message.content sargs = sargs.replace( self.bot.command_prefix[0] + "owner status", "") sargs = sargs.replace( self.bot.command_prefix[1] + "owner status", "") if sargs == "": await self.bot.say( ":x: You must specify a status to set to!") elif sargs == " online": await self.bot.change_presence( game=ctx.message.server.me.game, status=discord.Status.online) await self.bot.say("Done! Set my status to `online`!") elif sargs == " idle": await self.bot.change_presence( game=ctx.message.server.me.game, status=discord.Status.idle) await self.bot.say("Done! Set my status to `idle`!") elif sargs == " dnd": await self.bot.change_presence( game=ctx.message.server.me.game, status=discord.Status.dnd) await self.bot.say("Done! Set my status to `dnd`!") elif sargs == " invisible": await self.bot.change_presence( game=ctx.message.server.me.game, status=discord.Status.invisible) await self.bot.say( "Done! Set my status to `invisible`!") else: await self.bot.say( ":x: Not a valid status. Valid statuses are: `online`, `idle`, `dnd`, `invisible`" ) # Les chefs-d'oeuvre ne sont jamais que des tentatives heureuses elif args[1] == "name": unargs = ctx.message.content unargs = sargs.replace( self.bot.command_prefix[0] + "owner name", "") unargs = sargs.replace( self.bot.command_prefix[1] + "owner name", "") if unargs == "": await self.bot.say(x + "You must specify a name") else: await self.bot.edit_profile(username=str(unargs)) await self.bot.say( "Done! Changed my name successfully to `" + str(unargs) + "`") await self.bot.send_message( "`" + str(ctx.message.author) + "` changed my username to `" + str(unargs) + "`") elif args[1] == "eval": try: if args[2] != "": code = ctx.message.content.replace( self.bot.command_prefix[0] + "owner eval ", "") code = ctx.message.content.replace( self.bot.command_prefix[1] + "owner eval ", "") code = code.strip('` ') python = '```py\n{}\n```' result = None env = { 'bot': self.bot, 'ctx': ctx, 'message': ctx.message, 'server': ctx.message.server, 'channel': ctx.message.channel, 'author': ctx.message.author } env.update(globals()) try: result = eval(code, env) if inspect.isawaitable(result): result = await result except Exception as e: await self.bot.say( python.format( type(e).__name__ + ': ' + str(e))) return if type(result) is discord.Message: await self.bot.say( python.format("Successfully evaluated.")) else: await self.bot.say(python.format(result)) except IndexError: await self.bot.say(":x: Specify code to evaluate!") else: await self.bot.say(":x: Not a valid owner subcommand.") except IndexError: embed = discord.Embed( title="Owner Commands", description= "```css\n ===== [OwnerCmds] =====\nThe following are subcommands, meaning they are used with g_owner <subcommand> <args>\n ===== ===== ===== =====\n.game | Set my playing status.\n.nick | Set my nickname on the current server.\n.name | Set my username.\n.eval | Evaluate Python code.\n.status | Set my status.\n.shutdown | Shutdown the bot.\n.leaveserver | Leave the current server.\n ===== ===== ===== ===== \nThese are commands that sit on their own and are not owner subcommands.\n ===== ===== ===== =====\n.load | Load a cog.\n.reload | Reload a cog.\n.unload | Unload a cog.```", color=ctx.message.author.color).set_footer( text="Commands created in Discord.py") await self.bot.send_message(ctx.message.channel, content=None, embed=embed)
async def on_message(message): author = message.author msg = message.content channel = message.channel rolesAuthor = '' generateRole = '' try: for role in author.roles: rolesAuthor += role.name + '\n' except: pass if 'Basic' in rolesAuthor: generateRole += 'Basic' elif 'Classic' in rolesAuthor: generateRole += 'Classic' elif 'Famous' in rolesAuthor: generateRole += 'Famous' elif 'King' in rolesAuthor: generateRole += 'King' # .commands function if msg.startswith('.commands'): embed = discord.Embed( title='Commands', description= '``.buy`` to buy the Generator.\n``.generate (account type) (amount)`` to generate an account.\n``.gens`` shows your daily amout of gens left. (resets daily)\n``.stock`` to see which accounts are we offer or have in stock.\n``.about`` to get to know us better.\n``.reset`` to see when the generations will reset.\n``.verify (plan) (key)`` to redeeem a plan linked to a key.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .generate function if msg.startswith('.generate'): if generateRole != '': if 'generator' not in str(channel): embed = discord.Embed( title='Error', description='Try this command in #generator', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) else: gensTxt = open('Users/' + str(author) + '.txt').read() gensCount = re.search(r'(\d+)', gensTxt) if (generateRole == 'King' and int(gensCount.group(1)) == 30): embed = discord.Embed( title='Error', description= 'U have reached the ``30`` generation(s) so u have to wait ``24 hours``', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) elif (generateRole == 'Famous' and int(gensCount.group(1)) == 20): embed = discord.Embed( title='Error', description= 'U have reached the ``20`` generation(s) so u have to wait ``24 hours``', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) elif (generateRole == 'Classic' and int(gensCount.group(1)) == 15): embed = discord.Embed( title='Error', description= 'U have reached the ``15`` generation(s) so u have to wait ``24 hours``', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) elif (generateRole == 'Basic' and int(gensCount.group(1)) == 10): embed = discord.Embed( title='Error', description= 'U have reached the ``10`` generation(s) so u have to wait ``24 hours``', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) else: if msg == '.generate': pass else: accountTypes = re.search(r'.generate\s(\w+)', msg) generationCount = re.search(r'.generate\s\w+\s(\d+)', msg) if (int(generationCount.group(1)) + int(gensCount.group(1)) >= 31 and generateRole == 'King'): embed = discord.Embed( title='Error', description= 'The ``King`` role is not allowed to go above 30 generations.', color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) elif (int(generationCount.group(1)) + int(gensCount.group(1)) >= 21 and generateRole == 'Famous'): embed = discord.Embed( title='Error', description= 'The ``Famous`` role is not allowed to go above 20 generations.', color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) elif (int(generationCount.group(1)) + int(gensCount.group(1)) >= 16 and generateRole == 'Classic'): embed = discord.Embed( title='Error', description= 'The ``Classic`` role is not allowed to go above 15 generations.', color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) elif (int(generationCount.group(1)) + int(gensCount.group(1)) >= 11 and generateRole == 'Basic'): embed = discord.Embed( title='Error', description= 'The ``Basic`` role is not allowed to go above 10 generations.', color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) else: if accountTypes.group(1) in open( 'accountTypes.txt').read(): if generationCount is None: embed = discord.Embed( title='Error', description= 'No generation count has been typed, It should be ``.generate %s 1`` for example.' % accountTypes.group(1), color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) else: try: stockCount = len( open('Stock/' + accountTypes.group(1) + '.txt').readlines()) if stockCount < int( generationCount.group(1)): embed = discord.Embed( title='Error', description= '%s is out of stock or does not have %s accounts in stock.' % (accountTypes.group(1), generationCount.group(1)), color=0xC7223B) embed.set_footer( text= f"Requested by {author.name}") await channel.send(embed=embed) else: sendableAccount = '' with open('Stock/' + accountTypes.group(1) + '.txt') as myfile: head = [ next(myfile) for x in range( int( generationCount. group(1))) ] for item in head: sendableAccount += '``' + item.strip( ) + '`` ' f = open( 'Stock/' + accountTypes.group(1) + '.txt', 'r') d = f.readlines() f.close() f = open( 'Stock/' + accountTypes.group(1) + '.txt', 'w') for line in d: if item.strip( ) not in line: f.write(line) f.close() embed = discord.Embed( title=accountTypes.group(1), description=sendableAccount, color=0xC7223B) await client.send_message( author, embed=embed) embed = discord.Embed( title='Success', description= 'Sent %s %s %s account(s)!' % (str(message.author.mention), generationCount.group(1), accountTypes.group(1)), color=0xC7223B) embed.set_footer( text= f"Requested by {author.name}") await channel.send(embed=embed) with open( 'Users/' + str(author) + '.txt', 'U') as f: oldCount = f.read() newCount = int(oldCount) + int( generationCount.group(1)) f.close() with open( 'Users/' + str(author) + '.txt', 'w') as q: q.write(str(newCount)) q.close() except: embed = discord.Embed( title='Error', description= '``%s`` is not a supported account type.' % accountTypes.group(1), color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) pass else: embed = discord.Embed( title='Error', description= '``%s`` is not a supported account type.' % accountTypes.group(1), color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) pass else: embed = discord.Embed( title='Error', description= 'You can\'t generate that, you need a basic or higher role.\nYou can buy one here: https://shoppy.gg/@SypherrGen', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .about function if msg.startswith('.about'): embed = discord.Embed( title='About', description= 'We are SypherrGen, we are the cheapest and best generator out there.\nSypherrGen has an active staff team that helps you when needed.\nGenerate the accounts you need, for a good price.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .add function if msg.startswith('.add'): stockList = ['Developer', 'Cracker'] keyList = ['Developer'] stockAllowed = False keyAllowed = False for item in stockList: if item in rolesAuthor: stockAllowed = True for role in keyList: if role in rolesAuthor: keyAllowed = True if msg.startswith('.add key'): if keyAllowed == True: try: roleAdd = re.search(r'.add\skey\s(\w+)\s', msg) keySite = re.search(r'.add\s.*\s.*\s(.*)', msg) req = requests.get(keySite.group(1)) keyAdd = req.text f = open('Keys/' + roleAdd.group(1) + '.txt', 'r') d = f.readlines() f.close() f = open('Keys/' + roleAdd.group(1) + '.txt', 'a') for line in keyAdd: f.write(line) f.write('\n') f.close() embed = discord.Embed( title='Success', description='Added ``%s`` key(s) for ``%s``' % (len(keyAdd.split('\n')), roleAdd.group(1)), color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) except: embed = discord.Embed( title='Error', description='``%s`` is not a supported role.' % roleAdd.group(1), color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) elif keyAllowed == False: embed = discord.Embed( title='Error', description= 'This command is only accessible by Administrators.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) else: if stockAllowed == True: try: addType = re.search(r'.add\s(.*)\s', msg) stockSite = re.search(r'.add\s.*\s(.*)', msg) cleanStock = '' req = requests.get(stockSite.group(1)) stockAdd = req.text if addType.group(1) in open('accountTypes.txt').read(): try: # Check if the accountType typed has a .txt file and write to it. f = open('Stock/' + addType.group(1) + '.txt', 'r') d = f.readlines() f.close() f = open('Stock/' + addType.group(1) + '.txt', 'a') for line2 in stockAdd: line2 = line2.replace('\r', '') f.write(line2) f.close() embed = discord.Embed( title='Restock', description='Added ``%s`` account(s) for ``%s``' % (len(stockAdd.split('\n')), addType.group(1)), color=0xC7223B) embed.set_footer(text=f"Added by {author.name}") channel = discord.Object(id='510958653587849217') await channel.send(embed=embed) except: # If the accountType typed does not have a .txt file make one and let them try again. embed = discord.Embed( title='Error', description= 'The .txt containing the accounts was not found. Creating the .txt, try again now.', color=0xC7223B) embed.set_footer( text=f"Requested by {author.name}") await channel.send(embed=embed) f = open('Stock/' + addType.group(1) + '.txt', 'w+') f.close() else: embed = discord.Embed( title='Error', description='Invalid account type has been typed!', color=0xC7223B) await channel.send(embed=embed) except: pass else: embed = discord.Embed( title='Error', description= 'This command is only accessible by Administrators.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .buy function if msg.startswith('.buy'): # Embed message with shoppy.gg link. embed = discord.Embed( title='Buy', description='https://shoppy.gg/@SypherrGen to buy a plan.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .stock function if msg.startswith('.stock'): stockTypes = open('accountTypes.txt').read().splitlines() showStock = '' for item in stockTypes: # Get all lines of the text file and index them into the showStock string. if os.path.isfile('Stock/' + item + '.txt'): num_lines = sum(1 for line in open('Stock/' + item + '.txt')) showStock += '``' + item + ' - ' + str(num_lines) + '``\n' embed = discord.Embed(title='Stock', description=showStock, color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .verify function if msg.startswith('.verify'): try: planTyped = re.search(r'.verify\s(.*?)\s', msg) keyTyped = re.search(r'.verify\s.*\s(.*)', msg) keyList = open('Keys/' + planTyped.group(1) + '.txt').read().splitlines() strKeys = '' for item in keyList: # Get all keys from the typed keyList and add them to a string. strKeys += '**' + item + '**\n' if 'verify-key' not in str(channel): embed = discord.Embed( title='Error', description='Try this command in #verify-key', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) else: if keyTyped.group( 1 ) in strKeys: # If the typed key exists. it gives user the plan and removes the key from the list. embed = discord.Embed( title='Success', description=str(message.author.mention) + ' Successfully redeemed ``%s`` with key ``%s``' % (planTyped.group(1), keyTyped.group(1)), color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) f = open('Keys/' + planTyped.group(1) + '.txt', 'r') d = f.readlines() f.close() f = open('Keys/' + planTyped.group(1) + '.txt', 'w') for line in d: if line != keyTyped.group(1) + '\n': f.write(line) f.close() addUser = open('Users/' + str(author) + '.txt', 'w+') addUser.write('0') basicRole = discord.utils.get(author.server.roles, name=planTyped.group(1)) keyRole = await client.add_roles(author, basicRole) else: # If key does not exist, throw an error. embed = discord.Embed( title='Error', description='No role is linked to key ``%s``' % keyTyped.group(1), color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) except: embed = discord.Embed( title='Error', description= 'Command not valid. It should be .verify Famous 1234-5678-9012 for example.', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .gens function if msg.startswith('.gens'): gensTxt = open('Users/' + str(author) + '.txt').read() gensCount = re.search(r'(\d+)', gensTxt) embed = discord.Embed(title='Gens', description='U have made ``' + gensCount.group(1) + '`` generation(s).', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed) # .reset function if msg.startswith('.reset'): global startTime currentTime = startTime - time.time() seconds = timedelta(seconds=(currentTime)) hoursTime = str(seconds) normalTime = str(hoursTime).split('.')[0] embed = discord.Embed( title='Success', description='All generation counts will reset in ``' + normalTime + '``', color=0xC7223B) embed.set_footer(text=f"Requested by {author.name}") await channel.send(embed=embed)
import traceback # Just default intents and a `discord.Client` instance # We don't need a `commands.Bot` instance because we are not # creating text-based commands. intents = discord.Intents.default() client = discord.Client(intents=intents) # We need an `discord.app_commands.CommandTree` instance # to register application commands (slash commands in this case) tree = app_commands.CommandTree(client) # The guild in which this slash command will be registered. # As global commands can take up to an hour to propagate, it is ideal # to test it in a guild. TEST_GUILD = discord.Object(ID) @client.event async def on_ready(): print(f'Logged in as {client.user} (ID: {client.user.id})') print('------') # Sync the application command with Discord. await tree.sync(guild=TEST_GUILD) class Feedback(discord.ui.Modal, title='Feedback'): # Our modal classes MUST subclass `discord.ui.Modal`, # but the title can be whatever you want.
async def on_message(message): # Spielstatus if message.content.startswith('p.game') and message.author.id == keys.pmcid: game = message.content[7:] await client.change_presence(game=discord.Game(name=game, url="https://twitch.tv/pixelwerfer", type=1)) await client.send_message(message.channel, "Status erfolgreich zu {0} geändert".format(game)) # Nickname ändern # if message.content.startswith('p.nick') and message.author.id == keys.pmcid: # nick = message.content[7:] # await client.change_nickname(message.author, nick) # Pixels Liebling if message.content.startswith('p.pixels_liebling'): response = requests.get('https://media.giphy.com/media/3xz2BIXYagz5STg0xi/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="kaffee.gif", content="Jeder muss Pixel's Liebling kennen") # Uptime abrufen if message.content.startswith('p.uptime'): await client.send_message(message.channel, "Ich laufe seit {0} Stunden und {1} Minuten im Testbetrieb".format(hour, minutes)) # Python Hilfe if message.content.lower().startswith('p.python'): await client.send_message(message.channel, embed=hilfe.py_help()) # Hilfe if message.content.lower().startswith('p.help'): user = message.author await hilfe.hilfe(message.content[7:].lower(), user, len(message.content)) # Sysinfo if message.content.lower().startswith('p.sysinfo'): await client.send_message(message.channel, embed=hilfe.system_info()) # Bot Invite if message.content.lower().startswith('p.invite'): iembed = discord.Embed( title="Einfach dem Link folgen um den Bot einzuladen.", description="http://pixeldrohne.mystic-alchemy.com", color=0x8a2be2 ) await client.send_message(message.channel, embed=iembed) # Avatar abrufen if message.content.startswith('p.avatar'): if len(message.content) == 8: user = message.author response = requests.get(user.avatar_url, stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="avatar.jpg", content=message.author.name) if len(message.content) > 8: user = message.mentions[0] response = requests.get(user.avatar_url, stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="avatar.jpg", content=user.display_name) # Bot Remote if message.content.startswith('p.say') and message.channel == client.get_channel('347000675093315584'): msg = message.content[5:] await client.delete_message(message) await client.send_typing(discord.Object(id='269432704360120321')) await asyncio.sleep(2) await client.send_message(discord.Object(id='269432704360120321'), msg) # Bot Remote Embed if message.content.startswith('p.esay') and message.channel == client.get_channel('347000675093315584'): emsg = message.content[7:] embedmsg = discord.Embed(color=0x1213a6, description=emsg) await client.delete_message(message) await client.send_typing(discord.Object(id='269432704360120321')) await asyncio.sleep(2) await client.send_message(discord.Object(id='269432704360120321'), embed=embedmsg) # eine "Über" Sektion if message.content.startswith('p.about'): abemb = discord.Embed( color=0xad1457, title="Über", description="Sorry, hier gibt es noch nichts zu sehen.") await client.send_message(message.channel, embed=abemb) # Invite zur Heimat if message.content.lower().startswith('p.test'): embed = discord.Embed( title="Invite zum Heimat-/Testserver", description="http://discord.gg/sgDQjeH", color=0x8a2be2 ) await client.send_message(message.channel, embed=embed) # Zufälliges "falsches" Zitat if message.content.lower().startswith('p.zitat'): öffnen = open("config/zitate.txt", "r", encoding='utf-8') auswahl = öffnen.readlines() zitat = random.choice(auswahl) await client.send_message(message.channel, zitat) öffnen.close() # Zitat hinzufügen if message.content.lower().startswith('p.schreiben'): datei = open("config/zitate.txt", "a", encoding='utf-8') zitat = message.content[12:] datei.write("\n" + zitat) await client.send_message(message.channel, "Dein Zitat `{0}` wurde der Liste hinzugefügt.".format(zitat)) datei.close() # Coinflip if message.content.lower().startswith('p.coin'): choice = random.randint(1, 2) if choice == 1: await client.add_reaction(message, '🌑') if choice == 2: await client.add_reaction(message, '🌕') # Test, dass Bot reagieren kann if message.content.lower().startswith('p.response'): botmsg = await client.send_message(message.channel, "Akzeptierst du mich? 👍 oder 👎") await client.add_reaction(botmsg, "👍") await client.add_reaction(botmsg, "👎") global messageid messageid = botmsg.id global messageuserid messageuserid = message.author # Schere Stein Papier if message.content.lower().startswith("p.ssp"): ssp = ['schere', 'stein', 'papier'] wahl = random.choice(ssp) spieler = message.content.strip().split(" ")[1] if not spieler.lower() in ssp: await client.send_message(message.channel, "[SSP] Du musst Schere, Stein oder Papier wählen!") elif wahl == spieler.lower(): ergemb = discord.Embed(color=0xecde13, title="Unentschieden!", description="Wir haben das gleiche gewählt." "\n\n Du hast {sp} gewählt, ich " "habe {bot} gewählt.".format(sp=spieler.capitalize() , bot=wahl.capitalize())) await client.send_message(message.channel, embed=ergemb) elif (spieler.lower() == "schere" and wahl.lower() == "stein") or \ (spieler.lower() == "stein" and wahl.lower() == "papier") or \ (spieler.lower() == "papier" and wahl.lower() == "schere"): ergemb = discord.Embed(color=0xb21512, title="Verloren!", description="Yay! Ich habe gewonnen.\n\n" " Du hast {sp} gewählt, ich" " habe {bot}" " gewählt.".format( sp=spieler.capitalize(), bot=wahl.capitalize())) await client.send_message(message.channel, embed=ergemb) elif (wahl.lower() == "schere" and spieler.lower() == "stein") or \ (wahl.lower() == "stein" and spieler.lower() == "papier") or \ (wahl.lower() == "papier" and spieler.lower() == "schere"): ergemb = discord.Embed(color=0x71cc39, title="Gewonnen!", description="Du hast gegen mich gewonnen." " Jetzt bin ich traurig." "\n\n Du hast {sp} gewählt, ich " "habe {bot} gewählt.".format( sp=spieler.capitalize(), bot=wahl.capitalize())) await client.send_message(message.channel, embed=ergemb) #Roulette # TODO: Einsatz adden! if message.content.lower().startswith("p.roulette"): roulette = ['schwarz', 'rot'] wahl = random.choice(roulette) spieler = message.content.strip().split(" ")[1] if not spieler.lower() in roulette: await client.send_message(message.channel, "[Roulette] Du musst schon Rot oder Schwarz wählen!") elif wahl != spieler.lower(): ergemb = discord.Embed(color=0xb21512, title="Verloren!", description="Die Kugel ist auf {} gelandet. Schade eigentlich!".format(wahl.capitalize())) await client.send_message(message.channel, embed=ergemb) elif wahl == spieler.lower(): ergemb = discord.Embed(color=0x71cc39, title="Gewonnen!", description="Juhu! Die Kugel ist auf {} gelandet. Herzlichen Glückwunsch!".format(wahl.capitalize())) await client.send_message(message.channel, embed=ergemb) if message.content.startswith('p.join'): try: if client.is_voice_connected(message.server): try: voice_client = client.voice_client_in(message.server) await voice_client.disconnect() except AttributeError: await client.send_message(message.channel, "Ich bin doch in keinem Kanal, was willst du von mir?") except Exception as error: await client.send_message(message.channel, "Ein Error is aufgetreten:\n ```{error}```".format(error=error)) if not client.is_voice_connected(message.server): try: channel = message.author.voice.voice_channel await client.join_voice_channel(channel) except Exception as error: await client.send_message(message.channel, "Ein Error ist aufgetreten:\n" "```{error}```".format(error=error)) except Exception as error: await client.send_message(message.channel, "Ein Error ist aufgetreten:\n" "```{error}```".format(error=error)) if message.content.startswith('p.leave'): try: voice_client = client.voice_client_in(message.server) await voice_client.disconnect() except AttributeError: await client.send_message(message.channel, "Ich bin doch in keinem Kanal, was willst du von mir?") except Exception as error: await client.send_message(message.channel, "Ein Error is aufgetreten:\n ```{error}```".format(error=error)) if message.content.startswith('p.play'): yt_url = message.content[7:] if client.is_voice_connected(message.server): voice = client.voice_client_in(message.server) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ') players[message.server.id] = player player.volume = 0.03 player.start() elif not client.is_voice_connected(message.server): channel = message.author.voice.voice_channel voice = await client.join_voice_channel(channel) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ', ) players[message.server.id] = player player.volume = 0.03 player.start() # Dieses Blockkommentar ist für eine spätere Funktion gedacht. """if not players[message.server.id].is_playing(): if client.is_voice_connected(message.server): voice = client.voice_client_in(message.server) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ') player.volume = 0.03 player.start() elif not client.is_voice_connected(message.server): channel = message.author.voice.voice_channel voice = await client.join_voice_channel(channel) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ', ) player.volume = 0.03 player.start() else: if client.is_voice_connected(message.server): voice = client.voice_client_in(message.server) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ') player.volume = 0.03 player.start() elif not client.is_voice_connected(message.server): channel = message.author.voice.voice_channel voice = await client.join_voice_channel(channel) player = await voice.create_ytdl_player(yt_url, before_options=' -reconnect 1 -reconnect_streamed 1 ' '-reconnect_delay_max 5 ', ) player.volume = 0.08 player.start()""" if message.content.startswith('p.pause'): try: players[message.server.id].pause() except Exception as error: await client.send_message(message.channel, "Ein Error ist aufgetreten:\n ```{error}```".format(error=error)) if message.content.startswith('p.resume'): try: players[message.server.id].resume() except Exception as error: await client.send_message(message.channel, "Ein Error ist aufgetreten:\n ```{error}```".format(error=error)) if message.content.startswith('p.volume'): volume = int(message.content[9:]) if volume <= 100: players[message.server.id].volume = volume / 100 await client.send_message(message.channel, "Lautstärke erfolgreich " "auf {0} % eingestellt.".format(volume)) elif volume > 100: await client.send_message(message.channel, "Diese Lautstärke ist eindeutig **zu hoch**!") if message.content.startswith('p.stop'): try: players[message.server.id].stop() except Exception as error: await client.send_message(message.channel, "Ein Error ist aufgetreten:\n ```{error}```".format(error=error)) # Massenlöschung try: if message.content.lower().startswith('p.purge') and ((message.author.id in mods) or keys.pmcid or keys.pxlid): lim = int(message.content[8:]) + 1 await client.purge_from(message.channel, limit=lim) await client.send_message(message.channel, "Erfolgreich gelöscht.") except Exception as e: await client.send_message(message.channel, "Es ist ein Fehler aufgetreten: {e}".format(e=e)) # Mod hinzufügen if message.author.id == (keys.pmcid or keys.pxlid) and message.content.lower().startswith('p.madd'): user = message.mentions[0] mod = user.id madd = open("config/mods.txt", "a", encoding='utf-8') madd.write('"{0}"'.format(mod) + "\n") await client.send_message(message.channel, "{0} wurde erfolgreich den Mods hinzugefügt".format(user.name)) madd.close() # Anti invite if ('discord'.lower() in message.content.lower()) and (message.author.id not in keys.exceptions): if 'discord.me'.lower() in message.content.lower(): user = message.author aif = open("config/invite.txt", "r", encoding='utf-8') ainv = aif.readlines() anti = random.choice(ainv) await client.delete_message(message) await client.send_message(message.channel, anti + " " + user.mention) if 'discord.gg'.lower() in message.content.lower(): user = message.author aif = open("config/invite.txt", "r", encoding='utf-8') ainv = aif.readlines() anti = random.choice(ainv) await client.delete_message(message) await client.send_message(message.channel, anti + " " + user.mention) # Ab hier muss umgebaut werden if message.content.lower().startswith('p.ja'): choice = random.randint(1, 4) if choice == 1: response = requests.get('https://media.giphy.com/media/A3dD2XWfJ7tV6/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="ja.gif") if choice == 2: response = requests.get('https://media.giphy.com/media/XMBJ0l20sNWEM/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="ja.gif") if choice == 3: response = requests.get('https://media.giphy.com/media/BlVVi6LGpZZ7O/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="ja.gif") if choice == 4: response = requests.get('https://media.giphy.com/media/dZWJ0MdlA6W9W/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="ja.gif") if message.content.lower().startswith('p.nein'): response = requests.get('https://media.giphy.com/media/eXQPwwE8DFTZS/200w_d.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="nein.gif") if message.content.lower().startswith('p.tableflip'): response = requests.get('https://media.giphy.com/media/uKT0MWezNGewE/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="pixie.gif") if 'porg' in message.content.lower(): response = requests.get('https://media.giphy.com/media/3ohhwqOVlEbBxEbss0/giphy.gif', stream=True) await client.send_file(message.channel, io.BytesIO(response.raw.read()), filename="porg.gif") if message.content.lower().startswith('p.halt') and message.author.id == keys.pmcid: await client.logout() await asyncio.sleep(1) sys.exit(1)
def get_guild_prefixes(self, guild, *, local_inject=_prefix_callable): """Gets the guild prefixes.""" proxy_msg = discord.Object(id=None) proxy_msg.guild = guild return local_inject(self, proxy_msg)
### CONF #### import asyncio import json import discord from discord.ext import commands chan_dev = discord.Object(id="533699221073952768") with open("token.json", "r") as conffile: config = json.load(conffile) bot = commands.Bot( command_prefix="!", description= "description du bot voici les differentes commandes utilisables a l'heure actuelle " ) bot.remove_command('help') # this specifies what extensions to load when the bot starts up startup_extensions = [ "fonctions.message", "fonctions.clear", "fonctions.help", "fonctions.8loup", "fonctions.cryptomonnaie", "fonctions.lapiece", "fonctions.math", "fonctions.sondage", "fonctions.experience", "fonctions.music",
async def get_mod_role_ids(self, guild_id: int) -> List[int]: """ Gets the mod role ids for a guild id. """ return await self._config.guild(discord.Object(id=guild_id)).mod_role()
async def purge(self, ctx, *, args: str = None): '''Advanced purge command. Do `help purge` for usage examples and argument list. Arguments are parsed as command line arguments. Examples: Delete all messages within the last 200 containing the word "spam": `purge --check 200 --contains "spam"` Delete all messages within the last 100 from two members: `purge --user @runie @dave` Delete maximum 6 messages within the last 400 starting with "ham": `purge --check 400 --max 6 --starts "ham"` List of arguments: ``` --check <int> Total amount of messages the bot will check for deletion. --max <int> Total amount of messages the bot will delete. --bot Only delete messages from bots. --user member [...] Only delete messages from these members. --after message_id Start deleting after this message id. --before message_id Delete, at most, up until this message id. --contains <string> [...] Delete messages containing this string(s). --starts <string> [...] Delete messages starting with this string(s). --ends <string> [...] Delete messages ending with this string(s).```''' parser = NoExitArgumentParser(prog='purge', add_help=False, allow_abbrev=False) parser.add_argument( '-c', '--check', type=int, metavar='message_count', help='Total amount of messages checked for deletion.') parser.add_argument( '-m', '--max', type=int, metavar='message_count', help='Total amount of messages the bot will delete.') parser.add_argument('--bot', action='store_true', help='Only delete messages from bots.') parser.add_argument('-u', '--user', nargs='+', metavar='user', help='Only delete messages from this member(s).') parser.add_argument('-a', '--after', type=int, metavar='id', help='Start deleting after this message id.') parser.add_argument('-b', '--before', type=int, metavar='id', help='Delete, at most, up until this message id.') parser.add_argument('--contains', nargs='+', metavar='text', help='Delete messages containing this string(s).') parser.add_argument( '--starts', nargs='+', metavar='text', help='Delete messages starting with this string(s).') parser.add_argument('--ends', nargs='+', metavar='text', help='Delete messages ending with this string(s).') if args is None: await ctx.send('```\n{0}\n```'.format(parser.format_help())) return try: args = parser.parse_args(shlex.split(args)) except Exception as e: raise commands.CommandError(str(e).partition('error: ')[2]) preds = [ lambda m: m.id != ctx.message.id, lambda m: m.id != RULES_MSG_ID ] if args.user: converter = MaybeMemberConverter() members = [] for id in args.user: try: member = await converter.convert(ctx, id) members.append(member) except commands.CommandError: raise commands.CommandError( 'Unknown user: "******"'.format(id)) # yes, if both objects were discord.Member I could do m.author in members, # but since member can be FakeUser I need to do an explicit id comparison preds.append( lambda m: any(m.author.id == member.id for member in members)) if args.contains: preds.append(lambda m: any( (s in m.content) for s in args.contains)) if args.bot: preds.append(lambda m: m.author.bot) if args.starts: preds.append( lambda m: any(m.content.startswith(s) for s in args.starts)) if args.ends: preds.append( lambda m: any(m.content.endswith(s) for s in args.ends)) count = args.max deleted = 0 def predicate(message): nonlocal deleted if count is not None and deleted >= count: return False if all(pred(message) for pred in preds): deleted += 1 return True # limit is 100 be default limit = 100 after = None before = None # set to 512 if after flag is set if args.after: after = discord.Object(id=args.after) limit = PURGE_LIMIT if args.before: before = discord.Object(id=args.before) # if we actually want to manually specify it doe if args.check is not None: limit = max(0, min(PURGE_LIMIT, args.check)) try: deleted_messages = await ctx.channel.purge(limit=limit, check=predicate, before=before, after=after) except discord.HTTPException: raise commands.CommandError( 'Error occurred when deleting messages.') deleted_count = len(deleted_messages) log.info('%s purged %s messages in %s', po(ctx.author), deleted_count, po(ctx.guild)) await ctx.send('{0} messages deleted.'.format(deleted_count), delete_after=10)
async def do_unban(self, guild, user_id, reason): await self.ban_service.delete(guild.id, user_id) await guild.unban(discord.Object(id=user_id), reason=reason)
def on_member_remove(member): serverchannel = discord.Object(STATICS.channelname_Bot_channel) yield from client.send_message(serverchannel, "Bye Bye {0}".format(member.name))
async def MAIN(message, args, level, perms, TWOW_CENTRAL): if level == 1: await message.channel.send("Include the channel(s) to search in!") return included_args = { "channel": message.content.lower().find("channel:") > -1, "after": message.content.lower().find("after:") > -1, "before": message.content.lower().find("before:") > -1, "limit": message.content.lower().find("limit:") > -1 } if not included_args["channel"]: await message.channel.send("Include the channel(s) to search in!") return if not included_args["after"] and not included_args["limit"]: await message.channel.send("Include either an `after:` or a `limit:`!") return msg = message.content.lower() if msg[msg.find("channel:") + 8] == "[": end_index = msg[msg.find("channel:") + 8:].find("]") if end_index == -1: await message.channel.send("You forgot to close the square brackets!") return end_index += msg.find("channel:") + 8 try: channels = [int(x[2:-1]) for x in msg[msg.find("channel:") + 9:end_index].split(" ")] except ValueError: await message.channel.send(f"Invalid channel! Make sure all specified channels are valid.") return channels = [discord.utils.get(TWOW_CENTRAL.channels, id=x) for x in channels] channels = [x for x in channels if x is not None] else: for param in args[1:]: if param.lower().startswith("channel:"): try: channel = int(param[8:][2:-1]) break except ValueError: await message.channel.send(f"Invalid channel `{param[8:]}`! Make sure it's a valid channel.") return if discord.utils.get(TWOW_CENTRAL.channels, id=channel) is None: await message.channel.send(f"Invalid channel `{param[8:]}`! Make sure it's a valid channel.") return channels = [discord.utils.get(TWOW_CENTRAL.channels, id=channel)] after = None before = None limit = 100000 content = None for param in args[1:]: if param.lower().startswith("after:"): try: after = int(param[6:]) after = discord.Object(after) except ValueError: await message.channel.send(f"Invalid message ID for `after:` parameter!") return if param.lower().startswith("before:"): try: before = int(param[7:]) before = discord.Object(before) except ValueError: await message.channel.send(f"Invalid message ID for `before:` parameter!") return if param.lower().startswith("limit:"): try: limit = int(param[6:]) except ValueError: await message.channel.send(f"Invalid message ID for `limit:` parameter!") return if param.lower().startswith("content:"): end_index = msg[msg.find("content:") + 8:].find("]") if end_index == -1: await message.channel.send("You forgot to close the square brackets!") return end_index += msg.find("content:") + 8 content = msg[msg.find("content:") + 9:end_index] recorded_count = 0 counter = await message.channel.send(f"Searching... Found 0 messages so far.") messages = [] for chnl in channels: async for msg_history in chnl.history(limit=limit, before=before, after=after): if content is None or msg_history.content.lower().find(content) > -1: messages.append(msg_history) if len(messages) - recorded_count >= 1000: recorded_count += 1000 await counter.edit(content=f"Searching... Found {recorded_count} messages so far.") messages = [x for x in sorted(messages, key=lambda x: x.id) if (x.id != message.id and x.id != counter.id)] message_count = len(messages) oldest = messages[0] newest = messages[-1] await counter.edit(content=f"""**Finished searching.** Found {message_count} messages fitting the criteria. Oldest message: https://discordapp.com/channels/{oldest.guild.id}/{oldest.channel.id}/{oldest.id} Newest message: https://discordapp.com/channels/{newest.guild.id}/{newest.channel.id}/{newest.id} """.replace("\t", "")) return
def on_message(message): if message.content.startswith(STATICS.PREFIX): invoke = message.content[len(STATICS.PREFIX):].split(" ")[0] args = message.content.split(" ")[1:] if commands.__contains__(invoke): yield from commands.get(invoke).ex(args, message, client, invoke) else: yield from client.send_message( message.channel, embed=Embed(color=discord.Color.red(), description=("The command `%s` is not valid!" % invoke))) if message.content.startswith('?user'): try: user = message.mentions[0] userjoinedat = str(user.joined_at).split('.', 1)[0] usercreatedat = str(user.created_at).split('.', 1)[0] userembed = discord.Embed(title="Username:"******"User Info") userembed.add_field(name="Joined the server at:", value=userjoinedat) userembed.add_field(name="User Created at:", value=usercreatedat) userembed.add_field(name="Discriminator:", value=user.discriminator) userembed.add_field(name="User ID:", value=user.id) yield from client.send_message(message.channel, embed=userembed) except IndexError: yield from client.send_message( message.channel, "Ich konnte den User nicht finden.") except: yield from client.send_message(message.channel, "Sorry Error") finally: pass if message.content.startswith('?uptime'): yield from client.send_message( message.channel, "Ich bin schon {0} Tage {1} stunde/n und {2} minuten online auf {3}." .format(days, hour, minutes, message.server)) if message.content.lower().startswith("?test"): botmsg = yield from client.send_message(message.channel, "👍 oder 👎") yield from client.add_reaction(botmsg, "👍") yield from client.add_reaction(botmsg, "👎") global testmsgid testmsgid = botmsg.id global testmsguser testmsguser = message.author if message.content.lower().startswith("?Teams"): embed = discord.Embed( title="Command", color=600, # blue description= "**@Brainhelfer maketeams** [anzahl der spieler] [anzahl der Teams]\n" "Dann nach geh in den waiting room und gib join ein\n" "am ende wenn alle pätze voll sind werden alle gemoved\n" "oder mit **closeteams** gemoved wenn nicht alle pätze voll sind") embed.set_author( name="Command list", icon_url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png", url="https://discordapp.com/developers/applications ") embed.set_footer(text="Ein bot von Brainkackwitz") embed.set_thumbnail( url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png" ) yield from client.send_message(message.channel, embed=embed) if message.content.lower().startswith("?teams"): embed = discord.Embed( title="Command", color=600, # blue description= "**@Brainhelfer maketeams** [anzahl der spieler] [anzahl der Teams]\n" "Dann nach geh in den waiting room und gib join ein\n" "am ende wenn alle pätze voll sind werden alle gemoved\n" "oder mit **closeteams** gemoved wenn nicht alle pätze voll sind") embed.set_author( name="Command list", icon_url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png", url="https://discordapp.com/developers/applications ") embed.set_footer(text="Ein bot von Brainkackwitz") embed.set_thumbnail( url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png" ) yield from client.send_message(message.channel, embed=embed) if message.content.lower().startswith("?Team"): embed = discord.Embed( title="Command", color=600, # blue description= "**@Brainhelfer maketeams** [anzahl der spieler] [anzahl der Teams]\n" "Dann nach geh in den waiting room und gib join ein\n" "am ende wenn alle pätze voll sind werden alle gemoved\n" "oder mit **closeteams** gemoved wenn nicht alle pätze voll sind") embed.set_author( name="Command list", icon_url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png", url="https://discordapp.com/developers/applications ") embed.set_footer(text="Ein bot von Brainkackwitz") embed.set_thumbnail( url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png" ) yield from client.send_message(message.channel, embed=embed) if message.content.lower().startswith("?team"): embed = discord.Embed( title="Command", color=600, # blue description= "**@Brainhelfer maketeams** [anzahl der spieler] [anzahl der Teams]\n" "Dann nach geh in den waiting room und gib join ein\n" "am ende wenn alle pätze voll sind werden alle gemoved\n" "oder mit **closeteams** gemoved wenn nicht alle pätze voll sind") embed.set_author( name="Command list", icon_url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png", url="https://discordapp.com/developers/applications ") embed.set_footer(text="Ein bot von Brainkackwitz") embed.set_thumbnail( url= "http://img1.wikia.nocookie.net/__cb20070302203617/beamer/images/7/71/Zahnrad.png" ) yield from client.send_message(message.channel, embed=embed) if message.content.lower().startswith("?lol"): search = message.content[5:] driver = webdriver.Firefox() url = "https://euw.op.gg/summoner/userName="******"userName") inputElement.send_keys(search) inputElement.submit() try: time.sleep(5) elo = str(driver.find_element_by_class_name("TierRank").text) lp = str(driver.find_element_by_class_name("LeaguePoints").text) winr = str(driver.find_element_by_class_name("winratio").text) yield from client.send_message( message.channel, "Player " + search + "\n" + elo + "\n" + lp + "\n" + winr) #driver.find_element_by_xpath('//h3[@class="LC20lb" and not(contains(text(), "org")) and not(contains(text(), "wikipedia"))]').click() except: serverchannel = discord.Object(STATICS.channelname_Bot_channel) yield from client.send_message(message.channel, "Es gibt einen fehler!")
async def deactivate_infraction(self, infraction: utils.Infraction, send_log: bool = True) -> t.Dict[str, str]: """ Deactivate an active infraction and return a dictionary of lines to send in a mod log. The infraction is removed from Discord, marked as inactive in the database, and has its expiration task cancelled. If `send_log` is True, a mod log is sent for the deactivation of the infraction. Supported infraction types are mute and ban. Other types will raise a ValueError. """ guild = self.bot.get_guild(constants.Guild.id) mod_role = guild.get_role(constants.Roles.moderator) user_id = infraction["user"] _type = infraction["type"] _id = infraction["id"] reason = f"Infraction #{_id} expired or was pardoned." log.debug(f"Marking infraction #{_id} as inactive (expired).") log_content = None log_text = { "Member": str(user_id), "Actor": str(self.bot.user), "Reason": infraction["reason"] } try: if _type == "mute": user = guild.get_member(user_id) if user: # Remove the muted role. self.mod_log.ignore(Event.member_update, user.id) await user.remove_roles(self._muted_role, reason=reason) # DM the user about the expiration. notified = await utils.notify_pardon( user=user, title="You have been unmuted.", content="You may now send messages in the server.", icon_url=utils.INFRACTION_ICONS["mute"][1]) log_text["Member"] = f"{user.mention}(`{user.id}`)" log_text["DM"] = "Sent" if notified else "**Failed**" else: log.info( f"Failed to unmute user {user_id}: user not found") log_text["Failure"] = "User was not found in the guild." elif _type == "ban": user = discord.Object(user_id) self.mod_log.ignore(Event.member_unban, user_id) try: await guild.unban(user, reason=reason) except discord.NotFound: log.info( f"Failed to unban user {user_id}: no active ban found on Discord" ) log_text["Note"] = "No active ban found on Discord." else: raise ValueError( f"Attempted to deactivate an unsupported infraction #{_id} ({_type})!" ) except discord.Forbidden: log.warning( f"Failed to deactivate infraction #{_id} ({_type}): bot lacks permissions" ) log_text[ "Failure"] = f"The bot lacks permissions to do this (role hierarchy?)" log_content = mod_role.mention except discord.HTTPException as e: log.exception(f"Failed to deactivate infraction #{_id} ({_type})") log_text["Failure"] = f"HTTPException with code {e.code}." log_content = mod_role.mention # Check if the user is currently being watched by Big Brother. try: active_watch = await self.bot.api_client.get("bot/infractions", params={ "active": "true", "type": "watch", "user__id": user_id }) log_text["Watching"] = "Yes" if active_watch else "No" except ResponseCodeError: log.exception(f"Failed to fetch watch status for user {user_id}") log_text["Watching"] = "Unknown - failed to fetch watch status." try: # Mark infraction as inactive in the database. await self.bot.api_client.patch(f"bot/infractions/{_id}", json={"active": False}) except ResponseCodeError as e: log.exception(f"Failed to deactivate infraction #{_id} ({_type})") log_line = f"API request failed with code {e.status}." log_content = mod_role.mention # Append to an existing failure message if possible if "Failure" in log_text: log_text["Failure"] += f" {log_line}" else: log_text["Failure"] = log_line # Cancel the expiration task. if infraction["expires_at"] is not None: self.cancel_task(infraction["id"]) # Send a log message to the mod log. if send_log: log_title = f"expiration failed" if "Failure" in log_text else "expired" await self.mod_log.send_log_message( icon_url=utils.INFRACTION_ICONS[_type][1], colour=Colours.soft_green, title=f"Infraction {log_title}: {_type}", text="\n".join(f"{k}: {v}" for k, v in log_text.items()), footer=f"ID: {_id}", content=log_content, ) return log_text
async def raid( ctx, arg, arg2, arg3, arg4 ): #arg = gym name, arg2 = pokemon name, arg3 = level, arg4 = time remaining if ctx and ctx.message.channel.id == str(bot_channel) and str( arg2).lower() in pokemon: """example: ^raid "Canandagua National Bank Clock Tower" Lugia 5 45""" pokemon_id = find_pokemon_id(str(arg2).capitalize()) pokecp = find_pokecp(str(arg2).capitalize()) now = datetime.datetime.utcnow() + timedelta(minutes=int(arg4)) time = datetime.datetime.utcnow() + timedelta() try: cursor.execute("SELECT gym_id FROM gymdetails WHERE name LIKE '" + str(arg) + "%';") gym_id = str(cursor.fetchall()) gym_id = gym_id.split(',') gym_id = gym_id[0].split('((') cursor.execute("REPLACE INTO raid(" "gym_id, level, spawn, start, " "end, pokemon_id, cp, move_1, " "move_2, last_scanned)" " VALUES (" + str('{}').format(gym_id[1]) + ", " + str(arg3) + ", " + str("'{}'").format(time) + ", " + str("'{}'").format(time) + ", " + str("'{}'").format(now) + ", " + str(pokemon_id) + ", " + str(pokecp) + ", 1, 1, " + str("'{}'").format(time) + ");") #"VALUES (%s, %s, "+str("'{}'").format(time)+", "+str("'{}'").format(time)+", "+str("'{}'").format(now)+", %s, %s, 1, 1, "+str("'{}'").format(time)+");", (str(gym_id[1]), str(pokemon_id), str(arg3), str(arg5))) cursor.execute("UPDATE gym SET last_modified = '" + str(time) + "', last_scanned = '" + str(time) + "' WHERE gym_id = " + str(gym_id[1]) + ";") database.ping(True) database.commit() await bot.say('Successfully added your raid to the live map.') await bot.send_message( discord.Object(id=log_channel), str(ctx.message.author.name) + ' said there was a ' + str(arg2) + ' raid going on at ' + str(arg)) and print( str(ctx.message.author.name) + ' said there was a ' + str(arg2) + ' raid going on at ' + str(arg)) #await bot.say("VALUES ("+str('{}').format(gym_id[1])+", "+str(arg3)+", "+str("'{}'").format(time)+", "+str("'{}'").format(time)+", "+str("'{}'").format(now)+", "+str(pokemon_id)+", "+str(pokecp)+", 1, 1, "+str("'{}'").format(time)+");") #await bot.say("UPDATE gym SET last_modified = '"+str(time)+"', last_scanned = '"+str(time)+"' WHERE gym_id = "+str(gym_id[1])+";") except: #database.connect() database.rollback() await bot.say( 'Unsuccesful in database query, your raid was not added to the live map.' ) await bot.say( "Could not find `{}` in my database. Please check your gym name. \nuse `^gym gym-name` to try and look it up" .format(arg)) await bot.say("VALUES (" + str('{}').format(gym_id[1]) + ", " + str(arg3) + ", " + str("'{}'").format(time) + ", " + str("'{}'").format(time) + ", " + str("'{}'").format(now) + ", " + str(pokemon_id) + ", " + str(pokecp) + ", 1, 1, " + str("'{}'").format(time) + ");") await bot.say("UPDATE gym SET last_modified = '" + str(time) + "', last_scanned = '" + str(time) + "' WHERE gym_id = " + str(gym_id[1]) + ";") tb = traceback.print_exc(file=sys.stdout) print(tb)
async def unban(self, ctx: commands.Context, target: int, *, reason: Optional[str]) -> None: """Unbans the given target""" reason = reason or self.def_reason await ctx.guild.unban(discord.Object(id=target), reason=reason)
import discord import asyncio import random import json import os import datetime from discord.ext import commands import time import traceback prefix = ["s.", "s>", "s/"] bot = commands.Bot(command_prefix=prefix) unkown = discord.Object("399410266519109632") other = discord.Object("399410308587716609") class Error(): print('ErrorHandler loaded') print('------') @bot.event async def on_command_error(error, ctx): if isinstance(error, commands.CommandNotFound): error = discord.Embed(title=":warning: Error", description="Command attempted: `{}`".format( ctx.message.content)) error.set_footer(text=ctx.message.author, icon_url=ctx.message.author.avatar_url) error.set_author(name=ctx.message.server.name, icon_url=ctx.message.server.icon_url) await ctx.bot.send_message(unkown, embed=error)
async def unequip(self, ctx): color_roles = await self._get_guild_color_roles(ctx.guild) await ctx.author.remove_roles( *[discord.Object(i) for i in color_roles]) await ctx.message.add_reaction("👌")
async def action(self): try: # used to reset stuff while developing # (edit_message does weird stuff sometimes) # await self.edit_message(self.message, embed=embed.create_embed(description='')) try: # cardlife REST API queries # login to CardLife to get PublicId auth = requests.post( "https://live-auth.cardlifegame.com/api/auth/authenticate", json={ "EmailAddress": self.config["email"], "Password": self.config["password"] }) auth_json = auth.json() # get information about all servers lobby = requests.post( 'https://live-lobby.cardlifegame.com/api/client/games', json={"PublicId": auth_json["PublicId"]}) servers_json = lobby.json() except: # catch server errors # TODO: log failed server requests # print("Received invalid response from CardLife servers, skipping run...") return # skip run # create embed description self.record_uptime(servers_json["Games"]) title = "CardLife Online Servers (%s)" % len(servers_json["Games"]) description = '' highest_playercount = 0 for item in servers_json['Games']: playercount = '%s/%s' % (item['CurrentPlayers'], item['MaxPlayers']) if len(playercount) > highest_playercount: highest_playercount = len(playercount) # create online server list str online_official_servers = dict() for item in servers_json['Games']: if item['IsOfficial']: online_official_servers[str( item['Id'])] = item['WorldName'] if not item['HasPassword']: # create single line to describe server playercount = '%s/%s' % (item['CurrentPlayers'], item['MaxPlayers']) spaces = highest_playercount - len(playercount) description += '`' + (spaces * '.') + playercount + '`| ' description += '' + item['WorldName'] + '' if len(json.loads(item['ModInfo'])['orderedMods']) != 0: description += ' (**M**)' if item['HasPassword']: # contradiction; will never happen description += ' (**P**)' description += '\n' # create offline official server list offline_servers_str = '' for id in self.official_servers: if id not in online_official_servers: offline_servers_str += '**!** | ' + self.official_servers[ id] + '\n' for id in online_official_servers: self.official_servers[id] = online_official_servers[ id] # update server names if offline_servers_str != '': description += '\n**__Offline__**\n' + offline_servers_str footer = dict() footer['text'] = '(Unofficial) CardLife API' footer['icon_url'] = None em = embed.create_embed(description=description, footer=footer, colour=0xddae60, title=title) deleted_messages = list() # update status messages for msg in self.public_namespace.messages: message = discord.Object(id=msg) message.channel = discord.Object( id=self.public_namespace.messages[msg]) try: await self.edit_message(message, new_content=' ', embed=em) except discord.NotFound: deleted_messages.append( msg) # catch deleted/inaccessible messages except: # don't stop other updates due to one error pass # remove deleted messages for msg in deleted_messages: del (self.public_namespace.messages[msg]) # save modified files self.official_servers_data.content = self.official_servers self.official_servers_data.save() self.public_namespace.messages_file.content = self.public_namespace.messages self.public_namespace.messages_file.save() except: traceback.print_exc() pass
async def quit(self, message, args): await self.client.send_message(discord.Object('496185128171864065'), 'I am needed elsewhere! Farewell!'.format(message)) await self.client.close()
async def allowed_by_whitelist_blacklist( self, who: Optional[Union[discord.Member, discord.User]] = None, *, who_id: Optional[int] = None, guild_id: Optional[int] = None, role_ids: Optional[List[int]] = None, ) -> bool: """ This checks if a user or member is allowed to run things, as considered by Red's whitelist and blacklist. If given a user object, this function will check the global lists If given a member, this will additionally check guild lists If omiting a user or member, you must provide a value for ``who_id`` You may also provide a value for ``guild_id`` in this case If providing a member by guild and member ids, you should supply ``role_ids`` as well Parameters ---------- who : Optional[Union[discord.Member, discord.User]] The user or member object to check Other Parameters ---------------- who_id : Optional[int] The id of the user or member to check If not providing a value for ``who``, this is a required parameter. guild_id : Optional[int] When used in conjunction with a provided value for ``who_id``, checks the lists for the corresponding guild as well. role_ids : Optional[List[int]] When used with both ``who_id`` and ``guild_id``, checks the role ids provided. This is required for accurate checking of members in a guild if providing ids. Raises ------ TypeError Did not provide ``who`` or ``who_id`` Returns ------- bool `True` if user is allowed to run things, `False` otherwise """ # Contributor Note: # All config calls are delayed until needed in this section # All changes should be made keeping in mind that this is also used as a global check guild = None mocked = False # used for an accurate delayed role id expansion later. if not who: if not who_id: raise TypeError( "Must provide a value for either `who` or `who_id`") mocked = True who = discord.Object(id=who_id) if guild_id: guild = discord.Object(id=guild_id) else: guild = getattr(who, "guild", None) if await self.is_owner(who): return True global_whitelist = await self._whiteblacklist_cache.get_whitelist() if global_whitelist: if who.id not in global_whitelist: return False else: # blacklist is only used when whitelist doesn't exist. global_blacklist = await self._whiteblacklist_cache.get_blacklist() if who.id in global_blacklist: return False if guild: if guild.owner_id == who.id: return True # The delayed expansion of ids to check saves time in the DM case. # Converting to a set reduces the total lookup time in section if mocked: ids = {i for i in (who.id, *(role_ids or [])) if i != guild.id} else: # DEP-WARN # This uses member._roles (getattr is for the user case) # If this is removed upstream (undocumented) # there is a silent failure potential, and role blacklist/whitelists will break. ids = { i for i in (who.id, *(getattr(who, "_roles", []))) if i != guild.id } guild_whitelist = await self._whiteblacklist_cache.get_whitelist( guild) if guild_whitelist: if ids.isdisjoint(guild_whitelist): return False else: guild_blacklist = await self._whiteblacklist_cache.get_blacklist( guild) if not ids.isdisjoint(guild_blacklist): return False return True
async def on_ready(self): print('Logged in as: {0} (ID: {1})'.format( self.user.name, self.user.id)) # print(self.guilds) whitelist = config['Whitelist'] blacklist = config['Blacklist'] conn = pgsql_connect('tracker.config') cur = conn.cursor() for guild in self.guilds: if guild.name.lower() in [x for x in whitelist]: # Add Roles to DB for guild_role in guild.role_hierarchy: cur.execute(cur.mogrify("INSERT INTO roles (guild_id, role, role_id) VALUES (%s,%s,%s) ON CONFLICT (guild_id, role_id) DO UPDATE SET role = %s", (guild.id, guild_role.name, guild_role.id, guild_role.name))) conn.commit() # Add Member Info to DB memb_role_list = [] for memb in guild.members: # Add member/guild info to tables cur.execute(cur.mogrify(""" INSERT INTO user_names (guild_id, user_id, member_name, display_name) VALUES (%s,%s,%s,%s) ON CONFLICT (guild_id, user_id) DO UPDATE SET member_name = %s, display_name = %s""", (guild.id, memb.id, str(memb), memb.display_name, str(memb), memb.display_name))) for member_role in memb.roles: # Add member/role info to tables memb_role_list.append((guild.id, memb.id, member_role.id)) args_str = b','.join(cur.mogrify("(%s,%s,%s)", x) for x in memb_role_list) cur.execute(b'INSERT INTO user_roles (guild_id, user_id, role_id) VALUES %s ON CONFLICT (guild_id, role_id, user_id) DO NOTHING' % args_str) conn.commit() for channel in guild.channels: if (isinstance(channel, discord.channel.TextChannel) and channel.permissions_for(guild.me).read_messages) and ((channel.name.lower() in whitelist[guild.name].split('\n')[1:] or not whitelist[guild.name]) and blacklist_check(guild, channel, blacklist)): print("{}: #{}".format(guild.name, channel), end='') cur3 = conn.cursor() # Backlog logger firstmessage = None while True: if firstmessage is None: cur3.execute("""SELECT id FROM chatlog WHERE channel_id='{}' AND guild_id='{}' ORDER BY created_at ASC LIMIT 1""".format( channel.id, guild.id)) try: firstmessage = discord.Object( cur3.fetchone()[0]) except TypeError: firstmessage = None print( "\nNo first message found. Starting at most recent message.") try: message_list = [] count = 0 async for message in channel.history(limit=1000, before=firstmessage): count += 1 message_list.append(( guild.id, message.author.name, message.author.id, message.content, message.channel.name, channel.id, message.id, True if message.embeds else False, message.reactions.__str__() if message.reactions else None, message.channel_mentions.__str__() if message.channel_mentions else None, message.role_mentions.__str__() if message.role_mentions else None, message.mentions.__str__() if message.mentions else None, message.guild.name, message.created_at, message.edited_at)) firstmessage = message if count == 0: break args_str = b','.join(cur.mogrify( "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in message_list) cur.execute( b"INSERT INTO chatlog (guild_id, author, author_id, content, channel, channel_id, id, embeds, reactions, channel_mentions, role_mentions, mentions, guild, created_at, edited_at) VALUES " + args_str) conn.commit() print(".", end="") except discord.errors.Forbidden as e: print(e) break cur3.close() # New message logger cur2 = conn.cursor() cur2.execute("""SELECT id FROM chatlog WHERE channel_id='{}' AND guild_id='{}' ORDER BY created_at DESC LIMIT 1""".format( channel.id, guild.id)) try: lastmessage = discord.Object(cur2.fetchone()[0]) except TypeError: lastmessage = None print("No previous records found.") cur2.close() try: message_list = [] count = 0 async for message in channel.history(limit=None, after=lastmessage): count += 1 # print(message.created_at, message.author.name, message.content) message_list.append(( guild.id, message.author.name, message.author.id, message.content, message.channel.name, channel.id, message.id, True if message.embeds else False, message.reactions.__str__() if message.reactions else None, message.channel_mentions.__str__() if message.channel_mentions else None, message.role_mentions.__str__() if message.role_mentions else None, message.mentions.__str__() if message.mentions else None, message.guild.name, message.created_at, message.edited_at)) if count == 0: print(" <No new messages>") continue args_str = b','.join(cur.mogrify( "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in message_list) cur.execute( b"INSERT INTO chatlog (guild_id, author, author_id, content, channel, channel_id, id, embeds, reactions, channel_mentions, role_mentions, mentions, guild, created_at, edited_at) VALUES " + args_str) conn.commit() print(" [Added {} messages]".format(count)) except discord.errors.Forbidden as e: print(e) conn.close() print("Data connection closed.") print('Data collection completed. It is safe to end the script.') exit()
async def stream(self, ctx: commands.Context, member: discord.Member, duration: Expiry = None) -> None: """ Temporarily grant streaming permissions to a member for a given duration. A unit of time should be appended to the duration. Units (∗case-sensitive): \u2003`y` - years \u2003`m` - months∗ \u2003`w` - weeks \u2003`d` - days \u2003`h` - hours \u2003`M` - minutes∗ \u2003`s` - seconds Alternatively, an ISO 8601 timestamp can be provided for the duration. """ log.trace( f"Attempting to give temporary streaming permission to {member} ({member.id})." ) if duration is None: # Use default duration and convert back to datetime as Embed.timestamp doesn't support Arrow duration = arrow.utcnow() + timedelta( minutes=VideoPermission.default_permission_duration) duration = duration.datetime elif duration.tzinfo is None: # Make duration tz-aware. # ISODateTime could already include tzinfo, this check is so it isn't overwritten. duration.replace(tzinfo=timezone.utc) # Check if the member already has streaming permission already_allowed = any(Roles.video == role.id for role in member.roles) if already_allowed: await ctx.send( f"{Emojis.cross_mark} {member.mention} can already stream.") log.debug( f"{member} ({member.id}) already has permission to stream.") return # Schedule task to remove streaming permission from Member and add it to task cache self.scheduler.schedule_at(duration, member.id, self._revoke_streaming_permission(member)) await self.task_cache.set(member.id, duration.timestamp()) await member.add_roles(discord.Object(Roles.video), reason="Temporary streaming access granted") # Use embed as embed timestamps do timezone conversions. embed = discord.Embed( description=f"{Emojis.check_mark} {member.mention} can now stream.", colour=Colours.soft_green) embed.set_footer( text=f"Streaming permission has been given to {member} until") embed.timestamp = duration # Mention in content as mentions in embeds don't ping await ctx.send(content=member.mention, embed=embed) # Convert here for nicer logging revoke_time = format_infraction_with_duration(str(duration)) log.debug( f"Successfully gave {member} ({member.id}) permission to stream until {revoke_time}." )