Beispiel #1
0
    async def mail_task(self):
        try:
            while not self.broadsword.is_closed:
                self.cnx = DBMain()
                self.time_next = await self.cnx.storage_get("nextMailCheck")

                if self.time_next is not None:
                    self.time_next = datetime.datetime.fromtimestamp(float(self.time_next))
                    #if self.time_next <= await self.now():
                    if await self.now() >= self.time_next:
                        log.info("Start periodic check corp\\alliance mails.")
                        await self.mail_check()
                else:
                    await self.cnx.storage_add("nextMailCheck", await self.next_check(self.interval))
                for attr in ("cnx", "t_next", "t_now"):
                    self.__dict__.pop(attr,None)
                await asyncio.sleep(self.interval)
        except asyncio.CancelledError:
            pass
        except (OSError, discord.ConnectionClosed):
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.mail_task())
        except Exception:
            log.exception("An exception has occurred in {}: ".format(__name__))
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.mail_task())
Beispiel #2
0
 async def _refresh(self):
     try:
         self.custom_headers = {
             "User-Agent": self.user_agent,
             "Content-Type": "application/json",
             "Authorization": self.auth_string,
         }
         self.params = {
             "grant_type": self.grant_type,
             "refresh_token": self.stored_token["token_refresh"],
         }
         self.request = await aiohttp.post(self.url,
                                           params=self.params,
                                           headers=self.custom_headers)
         if self.request.status in [400, 403]:
             raise TokenInvalidError()
         self.response = await self.request.json()
         self.created = self.datetime.now().replace(microsecond=0)
         self.access_token = self.response["access_token"]
         self.refresh_token = self.response["refresh_token"]
         self.cnx = DBMain()
         await self.cnx.token_update(config.sso["character_id"],
                                     self.access_token, self.refresh_token,
                                     self.created)
     except Exception as e:
         log.exception("An exception has occurred in {}: ".format(__name__))
     finally:
         if config.bot["devMode"]:
             log.info("Old token: {}".format(
                 self.stored_token["token_access"]))
             log.info("New token: {}".format(self.access_token))
         await self._selfclean(("cnx"))
Beispiel #3
0
    async def auth_task(self):
        try:
            while not self.broadsword.is_closed:
                self.cnx = DBMain()

                self.pending = await self.cnx.auth_pending_select()
                #   self.pendings content:
                #      `id` int(11) NOT NULL AUTO_INCREMENT,
                #      `eve_name` varchar(365) DEFAULT NULL,
                #      `character_id` varchar(128) NOT NULL,
                #      `corporation_id` varchar(128) NOT NULL,
                #      `alliance_id` varchar(128) NOT NULL,
                #      `discord_id` varchar(64) NOT NULL,
                #      `active` varchar(10) NOT NULL,
                #      `pending` varchar(10) NOT NULL,
                #      `added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

                if self.pending is not None:
                    log.info("Do authorize for '{}'.".format(
                        self.pending["eve_name"]))
                    await self.auth()

                #await self._selfclean(("cnx", "pending"))
                await asyncio.sleep(self.interval)
        except asyncio.CancelledError:
            pass
        except (OSError, discord.ConnectionClosed):
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.auth_task())
        except Exception:
            log.exception("An exception has occurred in {}: ".format(__name__))
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.auth_task())
Beispiel #4
0
 async def on_member_remove(self, member):
     try:
         log.info("User '{}' left the server.".format(member))
         self.cnx = DBMain()
         await self.cnx.member_delete(member.id)
     except Exception:
         log.exception("An exception has occurred in {}: ".format(__name__))
     finally:
         await self._selfclean(("cnx"))
Beispiel #5
0
    async def mail_check(self):
        try:
            self.cnx = DBMain()
            self.latestMailID = await self.cnx.storage_get("latestMailID")
            if self.latestMailID is None:
                self.latestMailID = "0"
            self.maxID = self.latestMailID
            self.url = "https://api.eveonline.com/char/MailMessages.xml.aspx?keyID={0}&vCode={1}&characterID={2}" \
                        .format(config.evemails["keyID"], config.evemails["vCode"], config.evemails["characterID"])
            self.mails = await MailUtils.xml_request(self.url)
            self.mails = await MailUtils.xml_to_dict(self.mails, "mails")
            if self.mails is not None:
                for self.mail in self.mails:
                    if (self.mail["@toCorpOrAllianceID"] in config.evemails["fromIDs"]) and (self.mail["@messageID"] > self.maxID):
                        self.url = "https://api.eveonline.com/char/MailBodies.xml.aspx?keyID={0}&vCode={1}&characterID={2}&ids={3}"\
                                        .format(config.evemails["keyID"],\
                                                config.evemails["vCode"],\
                                                config.evemails["characterID"],\
                                                self.mail["@messageID"]\
                                                )
                        self.content = await MailUtils.xml_request(self.url)
                        self.content = await MailUtils.xml_to_dict(self.content, "content")
                        if self.content is not None:
                            self.content = await MailUtils.format_mailbody(self.content)
                            self.msg_split = await MailUtils.str_split(self.content, 1800)

                            #self.msg = "**------------------------------------**\n"
                            self.msg = "**-------------Start Mail-------------**\n"
                            self.msg += "**Mail By: **{}\n".format(self.mail["@senderName"])
                            self.msg += "**Sent Date: **{}\n".format(self.mail["@sentDate"])
                            self.msg += "**Title: ** {}\n".format(self.mail["@title"])
                            self.msg += "**Content: **\n"
                            self.msg += self.msg_split[0]

                            await self.cnx.message_add(self.msg, self.channel)
                            if len(self.msg_split) > 0:
                                for self.i in range(1, len(self.msg_split)):
                                    await self.cnx.message_add(self.msg_split[self.i], self.channel)

                            self.endmsg = "**--------------End Mail--------------**\n"
                            await self.cnx.message_add(self.endmsg, self.channel)

                            self.maxID = max(self.mail["@messageID"], self.maxID)

                if self.maxID > self.latestMailID:
                    await self.cnx.storage_add("latestMailID", self.maxID)
            else:
                log.warning("EVE Api service is unavailable.")
            await self.cnx.storage_update("nextMailCheck", await self.next_check(self.interval))
            return 0
        except Exception:
            log.exception("An exception has occurred in {}: ".format(__name__))
        finally:
            for attr in ("latestMailID", "maxID", "url",
                         "mails", "mail", "content", "msg_split",
                         "msg", "time_now", "time_next"):
                self.__dict__.pop(attr,None)
Beispiel #6
0
 async def _get_stored(self):
     try:
         self.cnx = DBMain()
         self.stored_token = await self.cnx.token_get(self.char_id)
         if config.bot["devMode"]:
             log.info("Stored token: {}".format(self.stored_token))
     except Exception as e:
         log.exception("An exception has occurred in {}: ".format(__name__))
     finally:
         await self._selfclean(("cnx"))
Beispiel #7
0
 async def member_id_list(self):
     try:
         self.cnx = DBMain()
         self.members = await self.cnx.member_select_all()
         await self._make_id_list()
         return self.list
     except Exception:
         log.exception("An exception has occurred in {}: ".format(__name__))
     finally:
         await self._selfclean(("cnx", "members", "member", "list"))
Beispiel #8
0
 async def db(self, ctx):
     try:
         self.cnx = DBMain()
         self.msg_id = await self.cnx.message_get_oldest()
         self.msg = await self.cnx.message_get(self.msg_id)
         log.info(self.msg)
         await self.broadsword.say("```{}```".format(self.msg))
     except Exception:
         log.exception("An exception has occurred in {}: ".format(__name__))
     finally:
         for attr in ("cnx", "temp_value"):
             self.__dict__.pop(attr, None)
Beispiel #9
0
 async def rename_task(self):
     try:
         while not self.broadsword.is_closed:
             self.server = self.broadsword.get_server(id=config.bot['guild'])
             self.cnx = DBMain()
             self.x = 0
             while self.x < 4:
                 self.id = await self.cnx.rename_get_oldest()
                 if self.id is None:
                     break
                 self.queued_rename = await self.cnx.rename_get(self.id)
                 if self.queued_rename is not None:
                     if self.queued_rename['discord_id'] is None:
                         await self.cnx.rename_delete(self.id)
                         continue
                     if self.queued_rename['nick'] is None:
                         await self.cnx.rename_delete(self.id)
                         continue
                     try:
                         self.member = self.server.get_member(self.queued_rename['discord_id'])
                         await self.broadsword.change_nickname(self.member, self.queued_rename['nick'])
                         await self.cnx.rename_delete(self.id)
                     except discord.Forbidden as e:
                         if self.queued_rename['discord_id'] == self.server.owner.id:
                             log.info("Owner cann't be renamed!")
                             await self.cnx.rename_delete(self.id)
                             continue
                         if e.text == "Privilege is too low...":
                             log.info("BroadswordBot needs more privileges for rename members!")
                             continue
                 else:
                     continue
                 self.x += 1
                 for attr in ("member", "queued_rename", "id"):
                     self.__dict__.pop(attr,None)
             del self.cnx
             await asyncio.sleep(10)
     except asyncio.CancelledError:
         pass
     except (OSError, discord.ConnectionClosed):
         self._task.cancel()
         self._task = self.broadsword.loop.create_task(self.rename_task())
     except Exception:
         log.exception("An exception has occurred in {}: ".format(__name__))
         self._task.cancel()
         self._task = self.broadsword.loop.create_task(self.rename_task())
Beispiel #10
0
    async def fill(self, ctx):
        try:
            self.cnx = DBMain()
            self.members = await UserdbUtils().member_id_list()
            self.server = self.broadsword.get_server(id=config.bot["guild"])
            for self.member in self.server.members:
                if not self.member.bot:
                    if self.member.id not in self.members:
                        log.info("User '{}' added to discord members db.".\
                            format(self.member)
                        )
                        await self.cnx.member_add(self.member.id)

            self.members = await UserdbUtils().member_id_list()
            self.authorized = await self.cnx.auth_users_select()
            for self.user in self.authorized:
                if self.user["discord_id"] in self.members:
                    await self.cnx.member_set_authorized(self.user["discord_id"])
        except Exception:
            log.exception("An exception has occurred in {}: ".format(__name__))
        finally:
            await self._selfclean(
                ("cnx", "authorized", "members", "member", "user")
            )
Beispiel #11
0
 async def message_task(self):
     try:
         while not self.broadsword.is_closed:
             self.cnx = DBMain()
             self.x = 0
             while self.x < 3:
                 self.id = await self.cnx.message_get_oldest()
                 if self.id is None:
                     break
                 self.queued_msg = await self.cnx.message_get(self.id)
                 if self.queued_msg is not None:
                     if self.queued_msg['channel_id'] is None:
                         await self.cnx.message_delete(self.id)
                         continue
                     if self.queued_msg['message'] is None:
                         await self.cnx.message_delete(self.id)
                         continue
                     self.channel = self.broadsword.get_channel(self.queued_msg['channel_id'])
                     await self.broadsword.send_message(self.channel, self.queued_msg['message'])
                     await self.cnx.message_delete(self.id)
                 else:
                     continue
                 self.x += 1
                 for attr in ("channel", "queued_msg", "id"):
                     self.__dict__.pop(attr,None)
             del self.cnx
             await asyncio.sleep(7)
     except asyncio.CancelledError:
         pass
     except (OSError, discord.ConnectionClosed):
         self._task.cancel()
         self._task = self.broadsword.loop.create_task(self.message_task())
     except Exception:
         log.exception("An exception has occurred in {}: ".format(__name__))
         self._task.cancel()
         self._task = self.broadsword.loop.create_task(self.message_task())
Beispiel #12
0
    async def auth_check(self):
        try:
            while not self.broadsword.is_closed:
                log.info("Start periodic check authorization.")
                self.users_left = False
                self.auth_groups = await AuthUtils().get_auth_group_ids()
                self.cnx = DBMain()
                self.auth_users = await self.cnx.auth_users_select()
                if self.auth_users is not None:
                    self.msg = "```Left members:"

                    for self.auth_user in self.auth_users:
                        self.member = self.server.get_member(
                            self.auth_user["discord_id"])
                        if self.member is not None:
                            if self.member == self.server.owner:
                                continue
                            self.is_exempt = await AuthUtils().is_auth_exempt(
                                self.member.roles)
                            if not self.is_exempt:
                                self.charinfo = await self.esi.char_get_details(
                                    self.auth_user["character_id"])
                                if self.charinfo is not None:
                                    if str(self.charinfo["alliance_id"]
                                           ) not in self.auth_groups:
                                        self.users_left = True
                                        log.info(
                                            "User '{}' as known as '{}' left alliance\\corporation".\
                                            format(self.member.nick, self.member)
                                        )
                                        self.msg += "\n'{}' as known as '{}'".\
                                            format(self.member, self.member.nick)
                                        await self.cnx.auth_user_disable(
                                            self.auth_user["character_id"])
                                        await self.broadsword.remove_roles(
                                            self.member, *self.member.roles)
                                        if config.auth["kickWhenLeaving"]:
                                            await self.broadsword.kick(
                                                self.member)
                                        else:
                                            await self.cnx.member_set_unauthorized(
                                                self.auth_user["discord_id"])
                                else:
                                    log.warning(
                                        "EVE services temprorary unavailable!")
                                    continue

                    self.msg += "```"
                    if self.users_left:
                        if config.auth["alertChannel"] != "":
                            self.channel = self.broadsword.get_channel(
                                config.auth["alertChannel"])
                            await self.broadsword.send_message(
                                self.channel, self.msg)
                        else:
                            await self.broadsword.send_message(
                                self.server.owner,
                                "Warning! alertChannel is not set!")
                del self.cnx
                await asyncio.sleep(self.interval)
        except asyncio.CancelledError:
            pass
        except (OSError, discord.ConnectionClosed):
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.auth_check())
        except Exception:
            log.exception("An exception has occurred in {}: ".format(__name__))
            self._task.cancel()
            self._task = self.broadsword.loop.create_task(self.auth_check())