Python discord.Activity() Examples
The following are 21
code examples of discord.Activity().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord
, or try the search function
.
Example #1
Source File: admin.py From discord_bot with MIT License | 6 votes |
def changegame(self, ctx, gameType: str, *, gameName: str): '''Ändert das derzeit spielende Spiel (BOT OWNER ONLY)''' gameType = gameType.lower() if gameType == 'playing': type = discord.Activity.playing elif gameType == 'watching': type = discord.Activity.watching elif gameType == 'listening': type = discord.Activity.listening elif gameType == 'streaming': type = discord.Activity.streaming guildsCount = len(self.bot.guilds) memberCount = len(list(self.bot.get_all_members())) gameName = gameName.format(guilds = guildsCount, members = memberCount) await self.bot.change_presence(activity=discord.Activity(type=type, name=gameName)) await ctx.send(f'**:ok:** Ändere das Spiel zu: {gameType} **{gameName}**')
Example #2
Source File: fivem.py From predacogs with MIT License | 6 votes |
def activitytype(self, ctx: commands.Context, *, activity: str): """ Choose which type of activity you want to see for the bot status. Available types: - playing - watching - listening """ activity_types = ["playing", "watching", "listening"] if not activity.lower() in activity_types: await ctx.send_help() return await self.config.activity_type.set(activity.lower()) await ctx.send(f"Activity type set to: {inline(activity.lower())}")
Example #3
Source File: utility.py From modmail with GNU Affero General Public License v3.0 | 6 votes |
def before_loop_presence(self): await self.bot.wait_for_connected() logger.line() activity, status = await self.set_presence() if activity is not None: msg = f"Activity set to: {activity.type.name.capitalize()} " if activity.type == ActivityType.listening: msg += f"to {activity.name}." else: msg += f"{activity.name}." logger.info(msg) else: logger.info("No activity has been set.") if status is not None: msg = f"Status set to: {status.value}." logger.info(msg) else: logger.info("No status has been set.") await asyncio.sleep(1800) logger.info("Starting presence loop.")
Example #4
Source File: botlist.py From xenon with GNU General Public License v3.0 | 6 votes |
def update_loop(self): await self.bot.wait_until_ready() while not self.bot.is_closed(): try: await self.bot.change_presence(activity=discord.Activity( name=f"{self.bot.config.prefix}help", type=discord.ActivityType.watching ), afk=False) if self.bot.config.dbl_token is not None and self.bot.is_primary_shard(): await self.update_discordbots_org() except: traceback.print_exc() finally: await asyncio.sleep(10 * 60)
Example #5
Source File: owner.py From RTFMbot with Mozilla Public License 2.0 | 6 votes |
def playing(self, ctx, media=""): """Update bot presence accordingly to invoke command""" # Need URL for streaming if not media: media = f"{self.bot.config['PREFIX']}info | {self.bot.config['PREFIX']}help" p_types = {'playing': 0, 'streaming': 1, 'listening': 2, 'watching': 3} activity = discord.Activity(name=media, type=p_types[ctx.invoked_with]) # Keep trace of it with open('config.yml', 'r') as file: stuff = yaml_load(file) stuff['STATUS_TYPE'] = p_types[ctx.invoked_with] stuff['STATUS'] = media with open('config.yml', 'w') as file: yaml_dump(stuff, file) self.bot.config = stuff await self.bot.change_presence(activity=activity)
Example #6
Source File: trustyavatar.py From Trusty-cogs with MIT License | 6 votes |
def get_activity(self, new_status: dict) -> tuple: """ This will return which avatar, status, and activity to use """ date = datetime.now() activity = None status = None if date.month == 12 and date.day <= 25: url = new_status["xmas"] activity = discord.Activity(name="Merry Christmas!", type=discord.ActivityType.playing) status = discord.Status.online elif (date.month == 12 and date.day >= 30) or (date.month == 1 and date.day == 1): url = new_status["link"] activity = discord.Activity(name="Happy New Year!", type=discord.ActivityType.playing) status = discord.Status.online else: url = new_status["link"] activity = discord.Activity( name=choice(new_status["game"]), type=choice(new_status["type"]) ) status = new_status["status"] return status, activity, url
Example #7
Source File: setstatus.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def setstatus(cmd, pld): """ :param cmd: The command object referenced in the command. :type cmd: sigma.core.mechanics.command.SigmaCommand :param pld: The payload with execution data and details. :type pld: sigma.core.mechanics.payload.CommandPayload """ if cmd.bot.cfg.pref.status_rotation: response = error('I can\'t, automatic rotation is enabled.') else: status = ' '.join(pld.args) activity = discord.Activity(type=discord.ActivityType.playing, name=status) await cmd.bot.change_presence(activity=activity) response = ok(f'New playing status set to {status}.') await pld.msg.channel.send(embed=response)
Example #8
Source File: main.py From discord_bot with MIT License | 5 votes |
def _randomGame(): #Check games.py to change the list of "games" to be played while True: guildCount = len(bot.guilds) memberCount = len(list(bot.get_all_members())) randomGame = random.choice(loadconfig.__games__) await bot.change_presence(activity=discord.Activity(type=randomGame[0], name=randomGame[1].format(guilds = guildCount, members = memberCount))) await asyncio.sleep(loadconfig.__gamesTimer__)
Example #9
Source File: info.py From Dozer with GNU General Public License v3.0 | 5 votes |
def _format_activities(activities: typing.Sequence[discord.Activity]) -> typing.List[str]: if not activities: return [] def format_activity(activity: discord.Activity) -> str: if isinstance(activity, discord.CustomActivity): return f"{activity.emoji} {activity.name}" elif isinstance(activity, discord.Spotify): return f'Listening to {activity.title} by {activity.artist} on Spotify' elif activity.type is discord.ActivityType.listening: return f'Listening to {activity.name}' # Special-cased to insert " to" else: return f'{activity.type.name.capitalize()} {activity.name}' # Some games show up twice in the list (e.g. "Rainbow Six Siege" and "Tom Clancy's Rainbow Six Siege") so we # need to dedup them by string similarity before displaying them matcher = SequenceMatcher(lambda c: not c.isalnum(), autojunk=False) filtered = [activities[0]] for activity in activities[1:]: matcher.set_seq2(activity.name) # Expensive metadata is computed about seq2, so change it less frequently for filtered_activity in filtered: matcher.set_seq1(filtered_activity.name) if matcher.quick_ratio() < 0.6 and matcher.ratio() < 0.6: # Use quick_ratio if we can as ratio is slow filtered.append(activity) break return [format_activity(activity) for activity in filtered]
Example #10
Source File: info.py From Dozer with GNU General Public License v3.0 | 5 votes |
def member(self, ctx, *, member: discord.Member = None): """Retrieve information about a member of the guild. If no arguments are passed, information about the author is used. **This command works without mentions.** Remove the '@' before your mention so you don't ping the person unnecessarily. You can pick a member by: - Username (`cooldude`) - Username and discriminator (`cooldude#1234`) - ID (`326749693969301506`) - Nickname - must be exact and is case-sensitive (`"Mr. Cool Dude III | Team 1234"`) - Mention (not recommended) (`@Mr Cool Dude III | Team 1234`) """ if member is None: member = ctx.author icon_url = member.avatar_url_as(static_format='png') embed = discord.Embed(title=member.display_name, description=f'{member!s} ({member.id})', color=member.color) embed.add_field(name='Bot Created' if member.bot else 'Account Created', value=member.created_at.strftime(self.datetime_format), inline=True) embed.add_field(name='Member Joined', value=member.joined_at.strftime(self.datetime_format), inline=True) if member.premium_since is not None: embed.add_field(name='Member Boosted', value=member.premium_since.strftime(self.datetime_format), inline=True) embed.add_field(name='Color', value=str(member.color).upper(), inline=True) status = 'DND' if member.status is discord.Status.dnd else member.status.name.title() if member.status is not discord.Status.offline: platforms = self.pluralize([platform for platform in ('web', 'desktop', 'mobile') if getattr(member, f'{platform}_status') is not discord.Status.offline]) status = f'{status} on {platforms}' activities = '\n'.join(self._format_activities(member.activities)) embed.add_field(name='Status and Activity', value=f'{status}\n{activities}', inline=True) embed.add_field(name='Roles', value=', '.join(role.name for role in member.roles[:0:-1]) or 'None') embed.add_field(name='Icon URL', value=icon_url) embed.set_thumbnail(url=icon_url) await ctx.send(embed=embed)
Example #11
Source File: help.py From csgo-queue-bot with GNU General Public License v3.0 | 5 votes |
def on_ready(self): """ Set presence to let users know the help command. """ activity = discord.Activity(type=discord.ActivityType.watching, name="noobs type q!help") await self.bot.change_presence(activity=activity)
Example #12
Source File: bot.py From pollmaster with MIT License | 5 votes |
def on_ready(self): self.owner = await self.fetch_user(SETTINGS.owner_id) mongo = AsyncIOMotorClient(SETTINGS.mongo_db) self.db = mongo.pollmaster self.session = aiohttp.ClientSession() with open('utils/emoji-compact.json', encoding='utf-8') as emojson: self.emoji_dict = json.load(emojson) self.pre = {entry['_id']: entry.get('prefix', 'pm!') async for entry in self.db.config.find({}, {'_id', 'prefix'})} await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="pm!help")) self.log.info(f'[Cluster#{self.cluster_name}] Ready called.') self.pipe.send(1) self.pipe.close()
Example #13
Source File: pollmaster.py From pollmaster with MIT License | 5 votes |
def on_ready(): bot.owner = await bot.fetch_user(SETTINGS.owner_id) mongo = AsyncIOMotorClient(SETTINGS.mongo_db) bot.db = mongo.pollmaster bot.session = aiohttp.ClientSession() print(bot.db) # load emoji list with open('utils/emoji-compact.json', encoding='utf-8') as emojson: bot.emoji_dict = json.load(emojson) # # check discord server configs # try: # db_server_ids = [entry['_id'] async for entry in bot.db.config.find({}, {})] # for server in bot.guilds: # if str(server.id) not in db_server_ids: # # create new config entry # await bot.db.config.update_one( # {'_id': str(server.id)}, # {'$set': {'prefix': 'pm!', 'admin_role': 'polladmin', 'user_role': 'polluser'}}, # upsert=True # ) # except: # print("Problem verifying servers.") # cache prefixes bot.pre = {entry['_id']: entry.get('prefix', 'pm!') async for entry in bot.db.config.find({}, {'_id', 'prefix'})} await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="pm!help")) print("Bot running.")
Example #14
Source File: DJCore.py From DJ5n4k3 with MIT License | 5 votes |
def on_ready(): print(f'Bot is ready! Logged as in: {bot.user}') await bot.change_presence(status=discord.Status.idle, activity=discord.Activity(type=discord.ActivityType.watching, name=f"your move | {os.getenv('PREFIX')}help"))
Example #15
Source File: status_rotation.py From apex-sigma-core with GNU General Public License v3.0 | 5 votes |
def status_clockwork(ev): """ :param ev: The event object referenced in the event. :type ev: sigma.core.mechanics.event.SigmaEvent """ while True: if ev.bot.is_ready(): if ev.bot.cfg.pref.status_rotation: if not status_cache: status_files = await ev.db[ev.db.db_nam].StatusFiles.find().to_list(None) [status_cache.append(status_file.get('text')) for status_file in status_files] if status_cache: status = status_cache.pop(secrets.randbelow(len(status_cache))) activity = discord.Activity(name=status, type=discord.ActivityType.playing) # noinspection PyBroadException try: if ev.bot.cfg.pref.dev_mode: status_type = discord.Status.dnd else: if ev.bot.latency > 5 or ev.bot.latency < 0: status_type = discord.Status.dnd elif ev.bot.latency > 2: status_type = discord.Status.idle else: status_type = discord.Status.online await ev.bot.change_presence(activity=activity, status=status_type) except Exception: pass await asyncio.sleep(60)
Example #16
Source File: discord_bot.py From xiaomi_uranus_chatbot with GNU General Public License v3.0 | 5 votes |
def on_ready(): """ Confirm the bot is ready """ DISCORD_LOGGER.info("Bot started as %s! Username is %s and ID is %s", BOT.user.name, BOT.user, BOT.user.id) activity = Activity(name='Xiaomi updates', type=ActivityType.watching) await BOT.change_presence(activity=activity) # Load all modules in modules list
Example #17
Source File: utility.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def set_presence(self, *, status=None, activity_type=None, activity_message=None): if status is None: status = self.bot.config.get("status") if activity_type is None: activity_type = self.bot.config.get("activity_type") url = None activity_message = (activity_message or self.bot.config["activity_message"]).strip() if activity_type is not None and not activity_message: logger.warning( 'No activity message found whilst activity is provided, defaults to "Modmail".' ) activity_message = "Modmail" if activity_type == ActivityType.listening: if activity_message.lower().startswith("to "): # The actual message is after listening to [...] # discord automatically add the "to" activity_message = activity_message[3:].strip() elif activity_type == ActivityType.streaming: url = self.bot.config["twitch_url"] if activity_type is not None: activity = discord.Activity(type=activity_type, name=activity_message, url=url) else: activity = None await self.bot.change_presence(activity=activity, status=status) return activity, status
Example #18
Source File: fivem.py From predacogs with MIT License | 5 votes |
def activitystream( self, ctx: commands.Context, streamer: str = None, *, streamtitle: str = None ): """ Choose if you want to put a Twitch stream for the bot status. Example: `[p]fivemset activitystream summit1g Come watch my stream!` You can use some arguments: - `{players}` will show how many players are connected. - `{total}` will show the total players the server can have. - `{server_ip}` will show the server ip. Advanced example: `[p]fivemset activitystream summit1g {players}/{total} players are connected on LifeRP, check out my stream!` """ # Some logics from https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/core/core_commands.py#L1017 if streamtitle: streamtitle = streamtitle.strip() if "twitch.tv/" not in streamer: streamer = "https://www.twitch.tv/" + streamer async with self.config.all() as config: config["streamer"] = streamer config["stream_title"] = streamtitle config["activity_type"] = "streaming" await ctx.send( "Activity stream set to:\n" + box(f"Streamer: {streamer}\nTitle : {streamtitle}") ) elif streamer is None or streamtitle is None: await ctx.send_help() return
Example #19
Source File: fivem.py From predacogs with MIT License | 5 votes |
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 )
Example #20
Source File: utility.py From modmail with GNU Affero General Public License v3.0 | 4 votes |
def activity(self, ctx, activity_type: str.lower, *, message: str = ""): """ Set an activity status for the bot. Possible activity types: - `playing` - `streaming` - `listening` - `watching` When activity type is set to `listening`, it must be followed by a "to": "listening to..." When activity type is set to `streaming`, you can set the linked twitch page: - `{prefix}config set twitch_url https://www.twitch.tv/somechannel/` To remove the current activity status: - `{prefix}activity clear` """ if activity_type == "clear": self.bot.config.remove("activity_type") self.bot.config.remove("activity_message") await self.bot.config.update() await self.set_presence() embed = discord.Embed(title="Activity Removed", color=self.bot.main_color) return await ctx.send(embed=embed) if not message: raise commands.MissingRequiredArgument(SimpleNamespace(name="message")) try: activity_type = ActivityType[activity_type] except KeyError: raise commands.MissingRequiredArgument(SimpleNamespace(name="activity")) activity, _ = await self.set_presence( activity_type=activity_type, activity_message=message ) self.bot.config["activity_type"] = activity.type.value self.bot.config["activity_message"] = activity.name await self.bot.config.update() msg = f"Activity set to: {activity.type.name.capitalize()} " if activity.type == ActivityType.listening: msg += f"to {activity.name}." else: msg += f"{activity.name}." embed = discord.Embed(title="Activity Changed", description=msg, color=self.bot.main_color) return await ctx.send(embed=embed)
Example #21
Source File: mangobyte.py From MangoByte with MIT License | 4 votes |
def on_ready(): global on_ready_has_run is_first_time = True if on_ready_has_run: is_first_time = False print("on_ready called again, waiting 10 seconds before processing") await asyncio.sleep(10) on_ready_has_run = True start_time = datetime.datetime.now() if is_first_time: print('Logged in as:\n{0} (ID: {0.id})'.format(bot.user)) print('Connecting to voice channels if specified in botdata.json ...') game = discord.Activity( name="DOTA 3 [?help]", type=discord.ActivityType.playing, start=datetime.datetime.utcnow()) await bot.change_presence(status=discord.Status.online, activity=game) audio_cog = bot.get_cog("Audio") artifact_cog = bot.get_cog("Artifact") await artifact_cog.load_card_sets() bot.help_command.cog = bot.get_cog("General") # stuff to help track/log the connection of voice channels connection_status = {} channel_tasks = [] for guildinfo in botdata.guildinfo_list(): if guildinfo.voicechannel is not None: channel_tasks.append(initial_channel_connect_wrapper(audio_cog, guildinfo)) connection_results = await asyncio.gather(*channel_tasks) for status in connection_results: if status not in connection_status: connection_status[status] = 0 connection_status[status] += 1 if is_first_time: print("\nupdating guilds") await loggingdb.update_guilds(bot.guilds) finished_text = "initialization finished" if not is_first_time: finished_text = "re-" + finished_text print(f"\n{finished_text}\n") message = "__**Initialization complete:**__" if not is_first_time: message = "__**Re-Initialization complete (shard prolly got poked):**__" for status in connection_status: message += f"\n{connection_status[status]} voice channels {status}" total_time = (datetime.datetime.now() - start_time).total_seconds() message += f"\n\ntook {int(total_time)} seconds" appinfo = await bot.application_info() if not settings.debug: await appinfo.owner.send(message)