Ejemplo n.º 1
0
 def __reboot(self, device, serial):
     LOGGER.info("#### Rebooting %s ####" % (device))
     ps = subprocess.Popen(["adb", "-s", serial, "reboot"],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
     output = ps.communicate()[0].decode('utf-8')
     return output
Ejemplo n.º 2
0
    def _wrap_func(*args, **kwargs):
        self = args[0]
        session = sessionmaker(bind=self.engine, expire_on_commit=False)

        # new session.   no connections are in use.
        self.session = session()
        try:
            # execute transaction statements.
            res = func(*args, **kwargs)
            # commit.  The pending changes above
            # are flushed via flush(), the Transaction
            # is committed, the Connection object closed
            # and discarded, the underlying DBAPI connection
            # returned to the connection pool.
            self.session.commit()
        except Exception as err:
            LOGGER.critical(err)
            # on rollback, the same closure of state
            # as that of commit proceeds.
            self.session.rollback()
            raise
        finally:
            # close the Session.  This will expunge any remaining
            # objects as well as reset any existing SessionTransaction
            # state.  Neither of these steps are usually essential.
            # However, if the commit() or rollback() itself experienced
            # an unanticipated internal failure (such as due to a mis-behaved
            # user-defined event handler), .close() will ensure that
            # invalid state is removed.
            self.session.close()
        return res
Ejemplo n.º 3
0
 async def on_ready(self):
     LOGGER.info('Bot is ready.')
     self.start_time = datetime.utcnow()
     await self.change_presence(activity=discord.Game(name=config.PLAYING))
     # make mentionable.
     self.command_prefix.extend(
         [f'<@!{self.user.id}> ', f'<@{self.user.id}> '])
Ejemplo n.º 4
0
 def reset_prefix(self, server_id: int) -> None:
     try:
         server_setting = self.session.query(
             coremodels.ServerSetting).filter(
                 coremodels.ServerSetting.server_id == server_id).one()
         server_setting.prefix = None
     except sqlalchemy.orm.exc.NoResultFound:
         LOGGER.warning(f"No Settings for server_id {server_id}")
Ejemplo n.º 5
0
 def get_poll(self, poll_id: str) -> Union[poll_models.Poll, None]:
     try:
         poll = self.session.query(poll_models.Poll).filter(
             poll_models.Poll.poll_id == poll_id).one()
     except sqlalchemy.orm.exc.NoResultFound:
         LOGGER.warning("Poll with ID %d does not exist" % poll_id)
         return None
     return poll
Ejemplo n.º 6
0
 def reset_moderator_roles(self, server_id):
     try:
         server_setting = self.session.query(
             coremodels.ServerSetting).filter(
                 coremodels.ServerSetting.server_id == server_id).one()
         server_setting.moderator_roles = []
     except sqlalchemy.orm.exc.NoResultFound:
         LOGGER.warning(f"No Settings for server_id {server_id}")
Ejemplo n.º 7
0
 def __reboot_list(self, device_names):
     LOGGER.info("#### Got list to reboot %s ####" % (str(device_names)))
     outputs = []
     devices = [(device_name, self.devices[device_name])
                for device_name in device_names]
     for device, serial in devices:
         output = self.__reboot(device, serial)
         outputs.append("%s : %s : %s" % (device, serial, output))
     return outputs
Ejemplo n.º 8
0
 async def simplepoll(self, ctx, poll_title, *options):
     LOGGER.info("Creating Poll: %s %s on Server %s" % (poll_title, options, ctx.guild))
     # create a new poll
     poll_id = str(uuid.uuid4())
     new_poll = Poll(poll_id, poll_title, list(options))
     # send it to discord
     msg, embed = new_poll.to_discord()
     sent_message: discord.Message = await ctx.channel.send(content=msg,
                                                            embed=embed)
     self.pollmanager.add_poll(poll=new_poll, received_message=ctx.message, sent_message=sent_message)
     # add reactions to the poll.
     for reaction in new_poll.reaction_to_option.keys():
         await sent_message.add_reaction(reaction)
Ejemplo n.º 9
0
 def get_poll_with_message_id(
         self, message_id: int) -> Union[poll_models.Poll, None]:
     try:
         poll = self.session.query(poll_models.Poll).filter(
             or_(poll_models.Poll.sent_message == str(message_id),
                 poll_models.Poll.received_message == str(
                     message_id))).one()
         return poll
     except sqlalchemy.orm.exc.NoResultFound:
         LOGGER.warning(
             "Poll with poll_message or trigger_message ID %d does not exist"
             % message_id)
     return None
Ejemplo n.º 10
0
 async def notify_servers(self, ctx, message):
     admin_ids = set()
     admins = set()
     for member in self.bot.get_all_members():
         if member.guild_permissions.administrator and not member.bot:
             if member.id not in admin_ids:
                 admins.add(member)
                 admin_ids.add(member.id)
     app = await self.bot.application_info()
     if app.team:
         owners = [m.mention for m in app.team.members]
     else:
         owners = [app.owner.mention]
     message_prefix = f"Hey there,\nYou are the administrator of a server on which I am and I got an important " \
                      f"notification from my owner(s) {' '.join(owners)}:\n\n"
     LOGGER.info(f"Admins I notify: {[a.name for a in admins]}")
     for admin in admins:
         try:
             await admin.send(message_prefix + message)
         except:
             LOGGER.error(f"Could not send notification to {admin.name}")
Ejemplo n.º 11
0
 def get_polls(self, age=None) -> List[poll_models.Poll]:
     LOGGER.info(f'Getting polls with age {age}')
     if age:
         since = datetime.datetime.now() - datetime.timedelta(days=age)
         LOGGER.info(f'since: {since}')
         polls = self.session.query(poll_models.Poll).filter(
             poll_models.Poll.creation_time >= since)
         LOGGER.info(f'polls: {polls}')
     else:
         polls = self.session.query(poll_models.Poll).filter()
     return polls
Ejemplo n.º 12
0
 async def on_command_error(self, ctx, error):
     if isinstance(error, commands.NoPrivateMessage):
         await ctx.author.send(
             'This command cannot be used in private messages.')
     elif isinstance(error, commands.DisabledCommand):
         await ctx.author.send(
             'Sorry. This command is disabled and cannot be used.')
     elif isinstance(error, commands.CommandInvokeError):
         LOGGER.critical(f'In {ctx.command.qualified_name}:')
         traceback.print_tb(error.original.__traceback__)
         LOGGER.critical(
             f'{error.original.__class__.__name__}: {error.original}')
     elif isinstance(error, commands.MissingRequiredArgument):
         await ctx.author.send(
             'Sorry. This command is not how this command works, !help <command_name> to display usage'
         )
     else:
         LOGGER.critical(error)
Ejemplo n.º 13
0
 def update_member(self, member: Member, access_level: int) -> None:
     if access_level > 0:
         LOGGER.info(f"Updating: {member} to lvl {access_level}")
         self.session.execute(
             self.generate_query(member.id, access_level,
                                 f'{member.name}#{member.discriminator}'))
Ejemplo n.º 14
0
 async def on_member_update(self, before, after):
     if before.roles != after.roles:
         LOGGER.info(f"Member {after} updated roles, updating access-level")
         self.update_member(member=after)
Ejemplo n.º 15
0
 async def on_member_remove(self, member):
     LOGGER.info(f"Member {member} left server, updating access-level")
     self.update_member(member=member)
Ejemplo n.º 16
0
 async def on_member_join(self, member):
     LOGGER.info(f"Member {member} joined server, updating access-level")
     self.update_member(member=member)
Ejemplo n.º 17
0
MIT License

Copyright (c) 2018 Breee@github

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

from utility.globals import LOGGER
from bot import Raidquaza

if __name__ == "__main__":
    LOGGER.info("Starting Bot.")
    bot = Raidquaza(description="")
    bot.run()
Ejemplo n.º 18
0
 def get_member_lvl(self, member: Member) -> int:
     curr_access_lvl = 0
     LOGGER.debug("member", member.name)
     LOGGER.debug("member", member.roles)
     for guild_id, roles in config.GUILDS.items():
         LOGGER.debug("guild ", guild_id)
         for role_id, access_level in roles.items():
             LOGGER.debug(f'role {role_id} = {access_level}')
             if role_id in [role.id for role in member.roles]:
                 LOGGER.debug(f"{member.name} has role: {role_id}")
                 LOGGER.debug(f"{member.name}  curr: {curr_access_lvl}")
                 if access_level > curr_access_lvl:
                     LOGGER.debug(f"{member.name}  new: {access_level}")
                     curr_access_lvl = access_level
     return curr_access_lvl