async def loop_presence(self): presence = config.presences[self.presence] text = re.sub("{GUILDS}", str(len(self.bot.guilds)), presence["activity"]["text"]) text = re.sub("{SHARDS}", str(self.bot.shard_count), text) text = re.sub("{USERS}", str(len(self.bot.guilds)), text) text = re.sub("{SUPPORT_INVITE}", config.support_invite, text) self.presence += 1 if self.presence == len(config.presences): self.presence = 0 if presence["activity"]["type"] == discord.Streaming: activity = discord.Streaming(name=text, url=presence["activity"]["url"]) else: activity = discord.Activity(name=text, type=presence["activity"]["prefix"]) if "{SHARD}" in text: for x in range(self.bot.shard_count): text = re.sub("{SHARD}", str(x + 1), text) activity.name = text await self.bot.change_presence(activity=activity, status=presence["status"], shard_id=x) return await self.bot.change_presence(activity=activity, status=presence["status"])
async def status_task(self): with open('config/playingstatus.json') as f: stat = json.load(f) while True: for stats in stat["status"]: if stat["status"][stats] == 'game': activity = discord.Game(name=stats) await self.bot.change_presence( status=discord.Status.online, activity=activity) if stat["status"][stats] == 'listening': activity = discord.Activity( type=discord.ActivityType.listening, name=stats) await self.bot.change_presence( status=discord.Status.online, activity=activity) if stat["status"][stats] == 'streaming': activity = discord.Streaming(name=stats, url='https://www.twitch.tv/') await self.bot.change_presence( status=discord.Status.online, activity=activity) if stat["status"][stats] == 'watching': activity = discord.Activity( type=discord.ActivityType.watching, name=stats) await self.bot.change_presence( status=discord.Status.online, activity=activity) await asyncio.sleep(300)
async def stream(ctx, *, message): # b'\xfc' await ctx.message.delete() stream = discord.Streaming( name=message, url="https://www.twitch.tv/monstercat", ) await bot.change_presence(activity=stream)
async def streaming(ctx, *, message): # await ctx.message.delete() stream = discord.Streaming( name=message, url=stream_url, ) await bot.change_presence(activity=stream)
async def on_ready(): print(f''' Logged in as [{bot.user}] ============================ ID: [{bot.user.id}] ============================ Default Prefix: [-] ============================ Servers: [{len(bot.guilds)}] ============================ Members: [{len(set(bot.get_all_members()))}] ============================ ''') print("bot is ready") while True: # Setting the "Playing" status await bot.change_presence(activity=discord.Game(name="with Darkness")) await asyncio.sleep(60) # Setting "Listening to" status await bot.change_presence( activity=discord.Activity(type=discord.ActivityType.listening, name="Life once in darkness -shadow")) await asyncio.sleep(60) # Setting "Watching" status await bot.change_presence(activity=discord.Activity( type=discord.ActivityType.watching, name="Shadows")) await asyncio.sleep(60) # Setting "Streaming" status await bot.change_presence( activity=discord.Streaming(name="Watching programmers code me!", url="https://discord.gg/hQywcDjZUT")) await asyncio.sleep(60)
async def streaming(self, ctx, *, message): await ctx.message.delete() stream = discord.Streaming( name=message, url="https://www.twitch.tv/zeenode", ) await self.bot.change_presence(activity=stream)
async def streaming(ctx, *, message): await ctx.message.delete() stream = discord.Streaming( name=message, url="https://www.twitch.tv/hentai", ) await bot.change_presence(activity=stream)
async def status_updater(self): while not self.bot.is_ready(): await asyncio.sleep( 3) # loop until the bot is ready to have a populated cache while not self.bot.is_closed() and not self.status_updates.cancelled(): try: # don't question any of these await self.bot.change_presence(activity=discord.Activity( type=discord.ActivityType.watching, name=choice(("machine", "the Discord latency", "watches", "the sunshine", "Discord tokens 😈", "annoying unicode nicknames", "your weeb avy", "what you eat", "my weight")))) await asyncio.sleep(60) await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=choice(("your input", "your neighbours", \ "you, I promise", "fighting chipmunks")))) await asyncio.sleep(60) await self.bot.change_presence( activity=discord.Streaming(name=choice(("and screaming", "and shouting", "silence", "chill")), url="https://twitch.tv/#")) await asyncio.sleep(60) await self.bot.change_presence(activity=discord.Game(name=choice(("your life", "basketball", "TicTacToe instead working", \ "by the rules make everybody else happy.", "for peanuts", "jokes", "in time", "spin the bottle", "attention", "our rules", "an old movie")))) await asyncio.sleep(60) except ConnectionClosed: pass
async def on_ready(): settings = FirebaseConnection.firebasefetch("settings") statustype = settings["status"]["statustype"] args = settings["status"]["args"] if statustype == "playing": message = " ".join([arg for arg in args]) await self.bot.change_presence(activity=discord.Game( name=message)) elif statustype == "streaming": message = " ".join([arg for arg in args[1:]]) await self.bot.change_presence( activity=discord.Streaming(name=message, url=args[0])) elif statustype == "listening": message = " ".join([arg for arg in args]) await self.bot.change_presence(activity=discord.Activity( type=discord.ActivityType.listening, name=message)) elif statustype == "watching": message = " ".join([arg for arg in args]) await self.bot.change_presence(activity=discord.Activity( type=discord.ActivityType.watching, name=message)) print("Bot is ready.")
async def on_ready(): with open("SentinelHelp.json", "r") as cogFile: data = json.load(cogFile) data = data["Cogs"] cogList = list(data.keys()) for cog in cogList: cog = ("Cogs." + cog) try: bot.load_extension(cog) print("Loaded", cog) except Exception as e: print("Error loading", cog, "e:", e) randNum = random.randint(1, 5) if randNum == 1: await bot.change_presence(activity=discord.Activity( type=discord.ActivityType.watching, name="Cache be a Moron [.s]")) elif randNum == 2: await bot.change_presence( activity=discord.Game("with Cache's Emotions [.s]")) elif randNum == 3: await bot.change_presence(activity=discord.Streaming( name="Idiot Simulator [.s]", url= "https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstleyVEVO" )) elif randNum == 4: await bot.change_presence(activity=discord.Game("with ur mom [.s]")) else: await bot.change_presence(activity=discord.Activity( type=discord.ActivityType.listening, name="Cache's bullshit [.s]")) print(bot.user.name, "successfully connected to Discord")
def __init__(self, loop) -> None: super().__init__(command_prefix=self.get_prefix, reconnect=True, help_command=help.HelpCommand(), loop=loop, activity=discord.Streaming(name=f'{config.Config(bot=self).prefix}help', url='https://www.twitch.tv/mrrandoooom')) self.text_permissions = discord.Permissions(read_messages=True, send_messages=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True, add_reactions=True) self.voice_permissions = discord.Permissions(connect=True, speak=True) self.log = logging.getLogger('bot') self.start_time = time.time() self.session = aiohttp.ClientSession(loop=self.loop) self.config = config.Config(bot=self) self.utils = utils.Utils(bot=self) self.commands_not_allowed_dms = {} self.guild_blacklist = {} self.default_guild_config = objects.DefaultGuildConfig() self.guild_configs = {} self.user_blacklist = {} self.default_user_config = objects.DefaultUserConfig() self.user_configs = {} self.time_format = '%A %d %B %Y at %H:%M' self.lavalink = None self.redis = None self.db = None
async def on_ready(): print('-----') print('-----') print("Created by I'm Joker") game = discord.Streaming(name="Nothing", url="https://www.twitch.tv/twitch") await client.change_presence(status=discord.Status.online, activity=game)
async def timer(): await client.wait_until_ready() global seconds while True: # "Who invited" code for guild in client.guilds: for invite in await guild.invites(): x = [invite.url, invite.uses, invite.inviter.id] before_invites.append(x) await asyncio.sleep(59) # sometimes this skips if it's on 60? # Presence await client.change_presence( activity=discord.Streaming(name=flair(users), url='https://twitch.tv/mehvix', twitch_name="Mehvix")) fp = random.choice(os.listdir("media/avatars")) with open('media/avatars/{}'.format(fp), 'rb') as f: try: await client.user.edit(avatar=f.read()) except discord.HTTPException: pass # Sometimes discord gets angry when the profile pic is changed a lot # Comic Code if str(str(str( datetime.now()).split(" ")[1]).split(".")[0])[:5] == "07:00": date = datetime.today().strftime('%Y/%m/%d') search = "https://www.gocomics.com/calvinandhobbes/{}".format(date) print(search) channel = client.get_channel(settings.notification_channel) await channel.send(search) await asyncio.sleep(2)
async def _change_bot_status(self): await self.bot.wait_until_ready() while True: await asyncio.sleep(10) config_data = await self._get_config_data() if not config_data["toggled"]: # await self._set_default_status(config_data) continue if config_data["ip"] is None: continue data_players = await self._get_data(config_data["ip"], "players") data_server = await self._get_data(config_data["ip"], "info") if data_players is None or data_server is None: await self._set_default_status(config_data) continue activity = discord.Activity( name=config_data["text"].format(**self._format_text_status( data_players, data_server, config_data)), type=self._activity_types(config_data["activity_type"]), ) if config_data["activity_type"] == "streaming": activity = discord.Streaming( url=config_data["streamer"], name=config_data["stream_title"].format( **self._format_text_status(data_players, data_server, config_data)), ) await self.bot.change_presence(status=self._status( config_data["status"]), activity=activity)
async def on_ready(): print("le bot est prêt.") await client.change_presence( activity=discord.Streaming(name='b!help', url=url)) channel = client.get_channel(801132629914025984) await channel.send(datetime.now().strftime("%d/%m/%Y %H:%M:%S") + "le bot est prêt.")
async def change_pres(ctx, *args): await ctx.message.delete() acts = ['g', 'l', 's', 'w'] wanted_act = args[0] wanted_subject = args[1] if wanted_act == acts[2]: if len(args) >= 3: wanted_link = args[2] else: final = "Arguments insufficient or incorrect - Streaming status needs to be provided with a url" await (await ctx.send(final)).delete(delay=3) return else: wanted_link = '' if wanted_act in acts: if wanted_act == acts[0]: await client.change_presence(activity=discord.Game( name=wanted_subject)) final = f'Activity set to **Playing {wanted_subject}**' elif wanted_act == acts[1]: await client.change_presence(activity=discord.Activity( type=discord.ActivityType.listening, name=wanted_subject)) final = f'Activity set to **Listening to {wanted_subject}**' elif wanted_act == acts[2]: await client.change_presence(activity=discord.Streaming( name=wanted_subject, url=wanted_link)) final = f'Activity set to **Streaming {wanted_subject} at {wanted_link}**' else: await client.change_presence(activity=discord.Activity( type=discord.ActivityType.watching, name=wanted_subject)) final = f'Activity set to **Watching {wanted_subject}**' else: final = f'Arguments insufficient or incorrect -{args, wanted_act, wanted_subject}' await (await ctx.send(final)).delete(delay=3)
async def change_discord_presence_streaming( self, ctx: commands.Context, stream_url: str, status: Optional[discord.Status] = discord.Status.online, *, activity_name: str): """Command handler for the `presence` subcommand `streaming`. This is a command that changes the bots Discord presence to a streaming activity with the specified name and stream URL. The Discord status can also be set via the optional status argument. Args: ctx (discord.ext.commands.Context): The context from which this command is invoked. stream_url (str): The URL of the stream. (The watch button will redirect to this link if clicked) status (Optional[discord.Status]): The status which should be displayed. activity_name (str): The name of whatever the bot should be streaming. """ # Everything other than Twitch probably won't work because of a clientside bug in Discord. # More info here: https://github.com/Rapptz/discord.py/issues/5118 activity = discord.Streaming(name=activity_name, url=stream_url) if "twitch" in stream_url: activity.platform = "Twitch" elif "youtube" in stream_url: activity.platform = "YouTube" else: activity.platform = None await self.bot.change_presence(activity=activity, status=status) await _notify_presence_change(ctx.channel, ctx.author)
async def activity_command(self, ctx, acType: str, *, acName: str): acType = acType.lower() if acType == 'playing': type_ = discord.ActivityType.playing elif acType == 'watching': type_ = discord.ActivityType.watching elif acType == 'listening': type_ = discord.ActivityType.listening try: if acType == 'streaming': await self.client.change_presence( activity=discord.Streaming(name='Canlı', url=acName)) else: await self.client.change_presence( activity=discord.Activity(type=type_, name=acName)) activityEmbed = discord.Embed( title="Aktivite değişikliği başarılı.", colour=0xffd500) await ctx.send(embed=activityEmbed) logger.info( f"Admin | Activity: {acName}({acType}) | Tarafından: {ctx.author}" ) except Exception as e: activityEmbed_2 = discord.Embed(title="Hata", description=f"{e}", colour=0xffd500) await ctx.send(embed=activityEmbed_2) logger.error(f"Admin | Activity | Error: {e}")
def presence(self): presence = self.config["presence"] if presence["type"].upper() not in ("WATCHING", "PLAYING", "STREAMING", "LISTENING"): raise ValueError( "'type' should be one of 'watching', 'playing', 'streaming' or 'listening', not %s" % presence["type"]) if presence["status"].upper() not in ("ONLINE", "IDLE", "DND", "OFFLINE", "INVISIBLE"): raise ValueError( "'status' should be one of 'online', 'idle', 'dnd', 'offline' or 'invisible', not %s" % presence["status"]) status = { "ONLINE": discord.Status.online, "IDLE": discord.Status.idle, "DND": discord.Status.dnd, "OFFLINE": discord.Status.offline, "INVISIBLE": discord.Status.offline }[presence["status"].upper()] return Presence({ "WATCHING": discord.Activity(type=discord.ActivityType.watching, name=presence["name"]), "STREAMING": discord.Streaming(name=presence["name"], url=presence["url"]), "PLAYING": discord.Game(name=presence["name"]), "LISTENING": discord.Activity(type=discord.ActivityType.listening, name=presence["name"]) }[presence["type"].upper()], status)
async def startdbl(self): if not self.has_started == 1: self.has_started = 1 while True: log.info("Getting all servers.") log.info("Attempting to update server count.") i = instance_tools.InstanceTools(self.bot.instances, self.bot.redis) guilds = await i.get_all_guilds() game = discord.Streaming(name=random.choice(stats2), url="https://www.twitch.tv/nekoboat") await self.bot.change_presence(activity=game) log.info("Servers: %s" % guilds) if self.bot.instance == 0: try: url = "https://discordbots.org/api/bots/310039170792030211/stats" payload = { "server_count": int(guilds), "shard_count": self.bot.shard_count } async with aiohttp.ClientSession() as cs: await cs.post( url, json=payload, headers={"Authorization": config.dbots_key}) log.info("Posted server count. {}".format(guilds)) except Exception as e: log.error('Failed to post server count\n{}: {}'.format( type(e).__name__, e)) try: async with aiohttp.ClientSession() as session: await session.post( 'https://bots.discord.pw/api/bots/310039170792030211/stats', headers={'Authorization': f'{config.dpw_key}'}, json={ "server_count": int(guilds), "shard_count": self.bot.shard_count }) except Exception as e: log.error(f"Failed to post to pw, {e}") try: url = "https://discord.services/api/bots/310039170792030211" payload = {"guild_count": int(guilds)} async with aiohttp.ClientSession() as cs: await cs.post( url, json=payload, headers={"Authorization": config.ds_key}) except Exception as e: log.error(f"Failed to post to ds, {e}") # try: # url = f"https://listcord.com/api/bot/{self.bot.user.id}/guilds" # async with aiohttp.ClientSession() as cs: # await cs.post(url, headers={"Authorization": config.listcord}, json={"guilds": int(guilds)}) # except Exception as e: # log.error(f"Failed to post to listcord, {e}") await asyncio.sleep(1800)
def __init__(self, shard_count=None, shard_ids=None, send=None): title = "%shelp | patreon.com/watora" % globprefix streamer = "https://www.twitch.tv/monstercat" game = discord.Streaming(url=streamer, name=title) intents = discord.Intents.default() super().__init__(command_prefix=_prefix_callable, case_insensitive=True, description='', shard_ids=shard_ids, shard_count=shard_count, activity=game, max_messages=None, intents=intents) self.pipe = send self.session = aiohttp.ClientSession(loop=self.loop) self.debug_mode = "" self.remove_command('help') self.init_ok = False self.tokens = dataIO.load_json("config/tokens.json") self.config = None self.now = None self.nowkpop = None self.mcnow = None self.prefixes_map = {} self.languages_map = {} self.owo_map = {} self.autosongs_map = {} self.loaded_languages = {} # Spotify Integration self.spotify = None
async def on_ready(): await client.change_presence( status=discord.Status.dnd, activity=discord.Streaming( platform='Twitch', url='https://www.youtube.com/watch?v=dQw4w9WgXcQ', name='.help'))
def create_activity(activity_type, name, **kwargs): """ set the bot's presence\n :param activity_type: str, name of the activity :param name: str, name of the activity itself :param kwargs: dict[str, Any], any other arguments that may be used :return: the created activity """ if activity_type == "game": activity = discord.Game(name=name) elif activity_type == "stream": activity = discord.Streaming(name=name, url=kwargs["url"]) elif activity_type == "listen": activity = discord.Activity(type=discord.ActivityType.listening, name=name) elif activity_type == "watch": activity = discord.Activity(type=discord.ActivityType.watching, name=name) elif activity_type == "custom": activity = discord.Activity(type=discord.ActivityType.custom, name=name) elif activity_type == "competing": activity = discord.Activity(type=discord.ActivityType.competing, name=name) else: raise ActivityNotFound(activity_type) return activity
async def on_ready(): print(f"Logged in as {client.user.name}({client.user.id}") await client.change_presence(status=discord.Status.online, activity=discord.Streaming( name="Making discordbot", url="https://www.twitch.tv/elraenn")) client.loop.create_task(status_task())
async def on_ready(): cursor.execute("""CREATE TABLE IF NOT EXISTS users ( name TEXT, id INT, cash BIGINT, rep INT, lvl INT, server_id INT )""") cursor.execute("""CREATE TABLE IF NOT EXISTS shop ( role_id INT, id INT, cost BIGINT )""") for guild in client.guilds: for member in guild.members: if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}" ).fetchone() is None: cursor.execute( f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 1, {guild.id})" ) else: pass connection.commit() print('Бот вошел в сеть') print('Создатель: М0ксек#1719') print('Создан: 03.06.20') print('Префикс: >') await client.change_presence( activity=discord.Streaming(name="+help", url="https://www.twitch.tv/d") )
async def stream(ctx, *, message): await ctx.message.delete() stream = discord.Streaming( name=message, url="https://twitch.tv/sny4zzz", ) await Client.change_presence(activity=stream)
async def change_status(self): await self.bot.wait_until_ready() status = cycle(self.status) details = cycle(self.details) state = cycle(self.state) time = cycle(self.time) while not self.bot.is_closed(): if await verify_cooldown(self.bot, "change_status", 60): current_time = next(time) if current_time == 0: current_status = next(status) current_details = next(details) if not self.bot.is_closed(): await self.bot.change_presence( activity=discord.Streaming(name=current_status, url=self.url, details=current_details) ) else: current_status = next(status) current_state = next(state) if not self.bot.is_closed(): await self.bot.change_presence( activity=discord.Game(name=current_status), status=current_state) await asyncio.sleep(60)
async def on_ready(): await bot.change_presence(activity=discord.Streaming( name=f"+-help | watching {get_members()} members", url="https://twitch.tv/classErase")) bot.load_extension("jishaku") for extension in inital_extension: bot.load_extension(extension)
async def on_member_remove(self, member): channel = discord.utils.get(member.guild.text_channels, name="welcome") await self.change_presence( activity=discord.Streaming(name=f"with {len(self.users)} viewers!", url="https://twitch.tv/kraken")) try: send_message = self.settings[str(member.guild.id)]["auto_message"] except KeyError: try: self.settings[str(member.guild.id)]["auto_message"] = True except KeyError: self.settings[str(member.guild.id)] = {} self.settings[str(member.guild.id)]["auto_message"] = True with open("settings.json", "w") as f: json.dump(self.settings, f, indent=4) send_message = self.settings[str(member.guild.id)]["auto_message"] if channel is None: return try: if send_message is True: await channel.send( f"We're sad to see you leave, **<@{member.id}>**... :frowning2:" ) except (discord.Forbidden, discord.HTTPException): pass
async def upd_presence(): while True: secs = time.time() - client.start_time days = round(secs // 86400) hours = round((secs - days * 86400) // 3600) minutes = round((secs - days * 86400 - hours * 3600) // 60) seconds = round(secs - days * 86400 - hours * 3600 - minutes * 60) days_text = pluralize_russian(days, "день", "дня", "дней") hours_text = pluralize_russian(hours, "час", "часа", "часов") minutes_text = pluralize_russian(minutes, "минута", "минуты", "минут") seconds_text = pluralize_russian(seconds, "секунда", "секунды", "секунд") uptime = ", ".join( filter(lambda x: bool(x), [ "{0} {1}".format(days, days_text) if days else "", "{0} {1}".format(hours, hours_text) if hours else "", "{0} {1}".format(minutes, minutes_text) if minutes else "", "{0} {1}".format(seconds, seconds_text) if seconds else "" ])) await client.change_presence(activity=discord.Streaming( name="Аптайм: %s" % uptime, url="https://twitch.tv/allformine")) await asyncio.sleep(5)