예제 #1
0
class FakeUser:
    nick = None
    display_name = "Twentysix"
    name = "Twentysix"
    id = 852499907842801726
    guild = FAKE_GUILD
    mention = "<@852499907842801726>"
    created_at = datetime.utcnow()
    joined_at = datetime.utcnow()
    avatar_url = "test.com"
    roles = {}
    activities = [Activity(name="fake activity"), Activity(name="spam")]
예제 #2
0
async def on_ready(bot):
    try:
        if not bot.STARTUP_COMPLETE:
            await initialize(bot, True)
            #shutdown handler for clean exit on linux
            try:
                for signame in ('SIGINT', 'SIGTERM'):
                    asyncio.get_event_loop().add_signal_handler(
                        getattr(signal, signame),
                        lambda: asyncio.ensure_future(
                            Utils.cleanExit(bot, signame)))
            except Exception as e:
                pass  #doesn't work on windows

            bot.start_time = datetime.utcnow()
            GearbotLogging.info("Loading cogs...")
            for extension in Configuration.get_master_var("COGS"):
                try:
                    bot.load_extension("Cogs." + extension)
                except Exception as e:
                    await handle_exception(f"Failed to load cog {extension}",
                                           bot, e)
            GearbotLogging.info("Cogs loaded")

            to_unload = Configuration.get_master_var("DISABLED_COMMANDS", [])
            for c in to_unload:
                bot.remove_command(c)

            bot.STARTUP_COMPLETE = True
            info = await bot.application_info()
            bot.loop.create_task(
                keepDBalive(bot))  # ping DB every hour so it doesn't run off
            gears = [
                Emoji.get_chat_emoji(e)
                for e in ["WOOD", "STONE", "IRON", "GOLD", "DIAMOND"]
            ]
            a = " ".join(gears)
            b = " ".join(reversed(gears))
            await GearbotLogging.bot_log(
                message=
                f"{a} All gears turning at full speed, {info.name} ready to go! {b}"
            )
            await bot.change_presence(
                activity=Activity(type=3, name='the gears turn'))
        else:
            await bot.change_presence(
                activity=Activity(type=3, name='the gears turn'))

        bot.missing_guilds = [g.id for g in bot.guilds]
        await fill_cache(bot)

    except Exception as e:
        await handle_exception("Ready event failure", bot, e)
예제 #3
0
파일: bot.py 프로젝트: brtwrst/dndbot
 def __init__(self, *args, **options):
     super().__init__(*args, **options)
     self.session = None
     with open('../state/config.json') as conffile:
         self.config = json.load(conffile)
     self.last_errors = []
     self.default_activity = Activity(name='other Characters (+help)',
                                      type=0)
     self.error_activity = Activity(name='! other Characters (+help)',
                                    type=0)
     self.error_string = 'Sorry, something went wrong. We will look into it.'
     self.mainguild = None
     self.state = DBConnector(db_path='sqlite:///../state/state.db.sqlite3')
예제 #4
0
 async def presence(self):
     with open("bot-settings/othersettings.json", "r") as f:
         data = load(f)
     presences = data["bot"]["presences"]
     ptype = choice(list(presences))
     text = choice(presences[ptype])
     if ptype == "playing":
         presence = Game(name=text+" | bc~help")
     elif ptype == "listening":
         presence = Activity(name=text+" | bc~help", type=ActivityType.listening)
     elif ptype == "watching":
         presence = Activity(name=text+" | bc~help", type=ActivityType.watching)
     await self.bot.change_presence(activity=presence)
예제 #5
0
    async def botstatus(
            self, ctx: Context, status: str,
            status_info: t.Literal["playing", "watching",
                                   "listening"]) -> None:
        """
        Change the status of the bot
        `botstatus playing <new status>` - Change playing status
        `botstatus watching <new status>` - Change watching status
        `botstatus listening <new status>` - Change listening status
        """
        statuses = ["playing", "watching", "listening"]
        if status.lower() not in statuses:
            await ctx.send("Invalid status type!")

        if status.lower() == "playing":
            try:
                await self.bot.change_presence(activity=Game(type=0,
                                                             name=status_info),
                                               status=Status.online)
                await ctx.send(
                    f"Successfully changed playing status to **{status_info}**"
                )
            except InvalidArgument as e:
                await ctx.send(e)
            except Exception as e:
                await ctx.send(e)

        elif status.lower() == "watching":
            try:
                await self.bot.change_presence(activity=Activity(
                    type=ActivityType.watching, name=status_info))
                await ctx.send(
                    f"Successfully changed watching status to **{status_info}**"
                )
            except InvalidArgument as e:
                await ctx.send(e)
            except Exception as e:
                await ctx.send(e)

        elif status.lower() == "listening":
            try:
                await self.bot.change_presence(activity=Activity(
                    type=ActivityType.listening, name=status_info))
                await ctx.send(
                    f"Successfully changed listening status to **{status_info}**"
                )
            except InvalidArgument as e:
                await ctx.send(e)
            except Exception as e:
                await ctx.send(e)
예제 #6
0
async def on_ready():
    errored_guilds = []
    await client.change_presence(activity=Activity(
        name=f'{token_name}/USD on CoinGecko',
        type=ActivityType.watching,
    ), )
    print(f'{dt.utcnow()} | Discord client is running.\n')
    while True:
        try:
            price = requests.get(
                f'https://api.coingecko.com/api/v3/coins/{MARKET_ID}').json(
                )['market_data']['current_price']['usd']
            for guild in client.guilds:
                try:
                    await guild.me.edit(
                        nick=f'{token_name} ${round(float(price), 2)}')
                except errors.Forbidden:
                    if guild not in errored_guilds:
                        print(
                            f'{dt.utcnow()} | {guild}:{guild.id} hasn\'t set '
                            f'nickname permissions for the bot!')
                    errored_guilds.append(guild)
                except Exception as e:
                    print(f'{dt.utcnow()} | Unknown error: {e}.')
        except requests.exceptions.HTTPError as e:
            print(f'{dt.utcnow()} | HTTP error: {e}.')
        finally:
            await asyncio.sleep(30)
예제 #7
0
def bot_setup():
	# path to environment variables
	env_path = '.env'
	load_dotenv(dotenv_path=env_path)

	# get data from .env
	prefix = os.getenv('PREFIX')
	key = os.getenv('DISCORD_BOT_KEY')
	activity_name = os.getenv('ACTIVITY_NAME')
	db_path = os.getenv('DB_PATH')
	# register activity, prefix, commands
	if activity_name is None:
		bot = commands.Bot(command_prefix=prefix)
	else:
		activity = Activity(name=activity_name, type=ActivityType.playing)
		bot = commands.Bot(command_prefix=prefix, activity=activity)
	add_cogs(bot,
			Cogs(bot),
			Roles(bot),
			Listener(bot),
			NewRoles(bot),
			Shitposting(bot),
			VoiceChannel(bot),
			Weather(bot),
			WowsCog(bot),
			Twitter_manager(bot),
	)
	return bot, key
예제 #8
0
파일: meta.py 프로젝트: DoobDev/Doob
 async def set(self):
     _type, _name = self.message.split(" ", maxsplit=1)
     await self.bot.change_presence(
         activity=Activity(
             name=_name, type=getattr(ActivityType, _type, ActivityType.playing)
         )
     )
예제 #9
0
 async def on_ready(self):
     logger.info(f'\n\nBot {self.user}is ready! \n\n')
     activity = Activity(
         name='$ajuda',
         type=ActivityType.listening,
     )
     await self.change_presence(activity=activity)
예제 #10
0
파일: bot.py 프로젝트: Odbdh/Only
async def on_ready():

    print("Бот запустился")

    await bot.change_presence(status=discord.Status.idle,
                              activity=Activity(name="Порнуху",
                                                type=ActivityType.watching))
예제 #11
0
    def __init__(self):
        super(Bot, self).__init__(command_prefix=PREFIX,
                                  help_command=HelpCommandCustom())
        self.activity = Activity(name="Starting", type=ActivityType.playing)

        self.logger = logging.getLogger('discord')
        self.logger.setLevel(logging.ERROR)
        handler = logging.FileHandler(filename='bot.log', encoding='utf-8')
        handler.setFormatter(logging.Formatter("%(asctime)s : %(message)s"))

        self.logger.addHandler(handler)

        self.guild_events = GuildEvents()

        self.add_cog(Chat())
        self.add_cog(Donate())
        self.add_cog(Music(self))
        self.add_cog(Profile())
        self.add_cog(Guild(
        ))  # Guild() in this row because in help command it is "Server"
        self.add_cog(Settings())
        self.add_cog(System(self))

        if not DEBUG:
            self.add_cog(TopGG(self))
예제 #12
0
    async def _change_presence(self):
        messages = loads(
            open('./data/activities.json', encoding='utf-8').read())
        shards = await self.disco.db.get_shards()
        guilds = sum(shard.guilds for shard in shards)
        players = sum(shard.players for shard in shards)

        self.disco.log.info('Alterando Presences em todas as Shards...')
        for shard in self.disco.shards:
            activity = choice(self._activities)
            message = choice(messages[activity.name]).format(
                website=WEBSITE_URL,
                prefix=self.disco.prefixes[0],
                guilds=guilds,
                donate=PATREON_DONATE_URL,
                players=players)

            try:
                await self.disco.change_presence(activity=Activity(
                    type=activity,
                    name=message + f' [{shard}]',
                    url=STREAMING_ACTIVITY_URL),
                                                 shard_id=shard)
            except (ConnectionClosed, PyMongoError):
                pass

        self.disco.log.info('Presences alteradas.')
예제 #13
0
 async def disable_cron(self, ctx):
     self.tick.cancel()
     await self.bot.change_presence(activity=Activity(
         type=ActivityType.unknown, name=""),
                                    status=None)
     await ctx.channel.send(":white_check_mark: 自動実行を無効にしました。")
     logger.info("Cron disabled manually.")
예제 #14
0
async def parse_args(context, *args):
    username = context.author.name + \
        "#" + context.author.discriminator
    print(f'{time.time()}: {username} entered \'fake\'')

    if not db_exists(context.guild.id):
        await bot.change_presence(activity=Activity(
            name=f"{len(bot.guilds)} servers", type=ActivityType.watching))
        db_new(context.guild.id, context.guild.name)

    await context.message.delete()
    print("Didn't delete (debug purpose)")

    name = None
    msg = None
    url = None

    if "http" in args[-1]:
        url = args[-1]
    if len(args) >= 2:
        last = len(args)
        if url:
            last -= 1

        msg = ' '.join(args[1:last])
        if url and not args[0].isdigit():
            name, _ = await best_name(args[0], context)
        else:
            name, url = await best_name(args[0], context)

    print((name, msg, url))
    print
    return (name, msg, url)
예제 #15
0
    async def set_activity(self, *args, text=None, activity=None):
        if activity:
            await self.client.change_presence(activity=activity)
            return

        if text == '':
            await self.client.change_presence(activity=None)
            return

        activities = ('playing', 'streaming', 'listening', 'watching')
        text_split = text.split(' ')
        _activity = text_split.pop(0).lower()
        if _activity not in activities:
            return False
        _type = activities.index(_activity)
        if _type == 2 and text_split[0].lower() == 'to':
            del text_split[0]
        if _type == 1:
            _url = text_split.pop(0)
        else:
            _url = None
        _name = ' '.join(text_split)
        await self.client.change_presence(
            activity=Activity(name=_name, url=_url, type=_type))
        return True
예제 #16
0
async def play_youtube_url(youtube_url, context, channel_voice):
    # Create StreamPlayer
    voice_client = await channel_voice.connect()

    # Download song
    await context.send(':robot: Fetching song ...')
    file_id = uuid.uuid1().hex
    yt = YouTube(youtube_url)
    song_title = yt.title
    filename = '{0}.{1}'.format(file_id, extension)
    yt.streams.get_audio_only().download(filename=file_id)

    # Send message to text channel
    await context.send(
        ':musical_keyboard: Playing {0} :musical_keyboard:'.format(song_title))

    # Setting bot status
    await bot.change_presence(
        activity=Activity(type=ActivityType.playing, name=song_title))

    # Play music
    voice_client.play(FFmpegPCMAudio(filename), after=lambda: print('done'))

    # Check if audio is playing
    while voice_client.is_playing():
        await asyncio.sleep(1)

    # Disconnect after the player has finished
    os.remove(filename)
    voice_client.stop()
    await voice_client.disconnect()

    # Setting bot status
    await bot.change_presence(None)
예제 #17
0
async def on_ready(bot):
    def get_status(option: str):
        if option == "idle":
            return Status.idle
        elif option == "dnd":
            return Status.dnd
        elif option == "offline":
            return Status.offline
        else:
            return Status.online

    def get_type(option: str):
        if option == "streaming":
            return ActivityType.streaming
        elif option == "listening":
            return ActivityType.listening
        elif option == "watching":
            return ActivityType.watching
        else:
            return ActivityType.playing

    logger.info("-" * 50)
    logger.info(f" - BOT Login : {bot.user}")
    logger.info(f" - Connected to ( {len(bot.guilds)} ) guilds!")
    logger.info("-" * 50)

    await bot.change_presence(
        status=get_status(config["status"]["status"]),
        activity=Activity(
            type=get_type(config["status"]["activity"]),
            name=config["status"]["name"]
        )
    )
예제 #18
0
파일: bot.py 프로젝트: the-garlic-os/parrot
    def __init__(
        self, *,
        prefix: str,
        admin_user_ids: Set[int],
        redis: Redis,
    ):
        super().__init__(
            command_prefix=prefix,
            owner_ids=admin_user_ids,
            case_insensitive=True,
            allowed_mentions=AllowedMentions.none(),
            activity=Activity(
                name=f"everyone ({prefix}help)",
                type=ActivityType.listening,
            ),
        )
        self.redis = redis
        self.http_session = aiohttp.ClientSession()

        self.registered_users = RedisSet(self.redis, "registered_users")
        self.learning_channels = RedisSet(self.redis, "learning_channels")
        self.speaking_channels = RedisSet(self.redis, "speaking_channels")

        self.corpora = CorpusManager(self)
        self.avatars = AvatarManager(self)

        self.load_extension("jishaku")
        self._load_folder("events")
        self._load_folder("commands")
예제 #19
0
async def on_ready():
    n_servers = len(client.guilds)
    activity = Activity(type=ActivityType.watching,
                        name=f"{n_servers} servers")
    await client.change_presence(status=Status.online, activity=activity)
    print("[READY] Bot is running.....")
    print(f"on {n_servers} servers")
예제 #20
0
async def on_guild_join(guild):
    print("Joined A new guild")
    print(guild.name)
    n_servers = len(client.guilds)
    activity = Activity(type=ActivityType.watching,
                        name=f"{n_servers} servers")
    await client.change_presence(status=Status.online, activity=activity)
예제 #21
0
 def cog_unload(self):
     self.tick.cancel()
     presence_type = ActivityType.unknown
     self.bot.change_presence(activity=Activity(type=presence_type,
                                                name=""),
                              status=None)
     logger.debug(f"Presense Changed to {presence_type}.")
예제 #22
0
파일: __init__.py 프로젝트: zzckrian/merlin
    async def on_ready(self):
        if not self.ready:
            self.guild = self.get_guild(776108158891982889)
            self.stdout = self.get_channel(808223116126846986)
            self.scheduler.start()
            self.scheduler.add_job(
                self.rules_reminder,
                CronTrigger(day_of_week=0, hour=12, minute=0, second=0))
            self.scheduler.add_job(self.pengingat_sholat,
                                   CronTrigger(hour=19, minute=37, second=0))

            #            embed = Embed(title="DEATH NOTE", description="11/02/21", color=0xff0963, timestamp=datetime.utcnow())
            #            field = [("X", "REASON : x", False),
            #                     ("CLIENT.ON EVERY TEXT", "x", False),
            #                     ("YOI GAK BRO", "YOI", False)]
            #            for name, value, inline in field:
            #                embed.add_field(name=name, value=value, inline=inline)
            #            embed.set_footer(text="^^^ x")
            #            embed.set_author(name="<-- Togi", icon_url="x")
            #            embed.set_thumbnail(url=self.guild.icon_url)
            #            embed.set_image(url="x")

            #            await channel.send(embed=embed)
            #            await channel.send(file=File("./data/x.png"))

            while not self.cogs_ready.all_ready():
                await sleep(0.5)

            await self.stdout.send("Bot jalan")
            self.ready = True
            print("Bot Ready")

        else:
            print("Bot Reconnected")

        # STATUS
        await bot.change_presence(
            activity=Activity(type=ActivityType.listening, name="Ar-Rahman"))
        await sleep(10)
        await bot.change_presence(
            activity=Activity(type=ActivityType.watching, name="you"))
        await sleep(10)
        await bot.change_presence(activity=Activity(
            type=ActivityType.playing, name="do you know how to make bot?"))
        await sleep(10)
        await bot.change_presence(activity=Activity(
            type=ActivityType.watching, name="how to make bot in discord"))
예제 #23
0
    async def on_ready(self):
        """Sets the bot's status and activity upon booting up"""

        await self.bot.change_presence(status=Status.online,
                                       activity=Activity(
                                           type=ActivityType.playing,
                                           name='e.help'))
        print('Bot is ready.')  # for debugging purposes
예제 #24
0
 async def setsong(self, ctx: Context, *, activity):
     if not self.bot.is_admin(ctx.author):
         return
     logger.info(f'Song changed to "{activity}" by {str(ctx.author)}')
     self.bot.state['game'] = None
     self.bot.state['song'] = activity
     return await self.bot.change_presence(
         activity=Activity(name=activity, type=ActivityType.listening))
예제 #25
0
    async def on_ready(self):
        channel = get_bot_dev_channel(self.bot)

        await self.bot.change_presence(activity=Activity(
            type=ActivityType.watching, name="Pemandangan Jogja"))
        await channel.send(
            ReadyMessage('storage/ready_message.json').get_random())
        print(f'{self.bot.user} has connected to Discord!')
예제 #26
0
    async def update_status(self):
        if self.game_datas:
            activity_str = f"{plural(len(self.game_datas), 'live game')}: {list(self.game_datas.keys())}"
        else:
            activity_str = f"site for new players: {DOMAIN}"

        activity = Activity(name=activity_str, type=ActivityType.watching)
        await self.bot.change_presence(activity=activity)
예제 #27
0
 async def enable_cron(self, ctx):
     await self._load_userdata()
     await self.bot.change_presence(activity=Activity(
         type=ActivityType.listening, name="Cron"),
                                    status=None)
     self.tick.start()
     await ctx.channel.send(":white_check_mark: 自動実行を有効にしました。")
     logger.info("Cron enabled manually.")
예제 #28
0
 async def on_ready(self):
     await self.bot.change_presence(
         activity=Activity(
             type=ActivityType.watching,
             name=f"{self.bot.command_prefix}help for docs",
         ),
         status="!help for docs",
     )
예제 #29
0
        async def on_ready():
            """
            Set the bot status on discord
            """
            if os.name == 'nt':
                print('Ready')

            await self.bot.change_presence(
                activity=Activity(type=ActivityType.playing, name='!game'))
예제 #30
0
 async def startup(self):
     await self.wait_until_ready()
     self._signal()
     await self.change_presence(activity=Activity(
         type=ActivityType.watching, name="/move | git.io/JOOyt"))
     print('Logged in as')
     print(self.user.name)
     print(self.user.id)
     print('------')