Example #1
0
def add_university(request):
    if request.method == "POST":
        uni_name = request.POST['uni_name']
        uni_domain = request.POST['uni_domain']

        if University.objects.filter(name = uni_name).exists():
            # https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook
            webhookURL = os.getenv("WEBHOOK_URL")
            webhook = discord.Webhook.from_url(
                webhookURL, adapter=discord.RequestsWebhookAdapter())
            embed = discord.Embed(
                title="Error", description="[USER] tried to add an already existing university to the database", colour=0xff413b)
            embed.add_field(name="University name", value=uni_name)
            embed.add_field(name="University domain", value=uni_domain)
            webhook.send(embed=embed)

            return render(request, 'add_university.html', {"error": "The university already exists!"})

        if University.objects.filter(domain=uni_domain).exists():
            # https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook
            webhookURL = os.getenv("WEBHOOK_URL")
            webhook = discord.Webhook.from_url(
                webhookURL, adapter=discord.RequestsWebhookAdapter())
            embed = discord.Embed(
                title="Error", description="[USER] tried to add an already existing university to the database", colour=0xff413b)
            embed.add_field(name="University name", value=uni_name)
            embed.add_field(name="University domain", value=uni_domain)
            webhook.send(embed=embed)

            return render(request, 'add_university.html', {"error": "The university already exists!"})

        else:
            newUni = University(name=uni_name, domain=uni_domain)
            newUni.save()

            print("Saved university object")

            # https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook
            webhookURL = os.getenv("WEBHOOK_URL")
            webhook = discord.Webhook.from_url(
                webhookURL, adapter=discord.RequestsWebhookAdapter())
            embed = discord.Embed(
                title="New University", description="[USER] added a new university to the database", colour=0x47ff8e)
            embed.add_field(name="University name", value=uni_name)
            embed.add_field(name="University domain", value=uni_domain)
            webhook.send(embed=embed)

            return render(request, 'add_university.html', {"success": "Added university to the database, you should automatically be sent to the public university list in a few seconds!"})
    return render(request, 'add_university.html', {})
Example #2
0
 def __init__(self):
     webhook_id = config.DISCORD_WEBHOOK_ID
     webhook_token = config.DISCORD_WEBHOOK_TOKEN
     self.webhook = discord.Webhook.partial(
         webhook_id,
         webhook_token,
         adapter=discord.RequestsWebhookAdapter())
Example #3
0
    async def on_member_remove(self, user: discord.Member):
        data = await self.bot.db.fetchrow(
            'SELECT l.id, l.token, l.memberleave, m.logging FROM config.logging l INNER JOIN config.modules m ON l.sid = m.sid WHERE l.sid = $1',
            user.guild.id)
        if not data or not data['memberleave'] or not data['memberleave']:
            return

        since_joined_guild = (datetime.datetime.now() - user.joined_at).days
        embed = discord.Embed(color=std.normal_color, title = 'LOGGING [LEAVE]')
        embed.set_thumbnail(url=user.avatar_url)
        embed.timestamp = datetime.datetime.utcnow()
        embed.description = f'{std.outbox_emoji} {user} hat den Discord verlassen.'
        embed.add_field(name=f'{std.info_emoji} **__User__**',
                        value=f'{std.nametag_emoji} {user}\n'
                              f'{std.botdev_emoji} {user.id}\n',
                        inline=False)
        embed.add_field(name=f'{std.date_emoji} Tage auf dem Server', value=str(since_joined_guild), inline=False)
        roles = [role.mention for role in user.roles if role.name != '@everyone']
        embed.add_field(name=f'{std.mention_emoji} **__Rollen__**',
                        value=' '.join(roles) if len(roles) != 0 else '-----')
        embed.timestamp = datetime.datetime.utcnow()
        embed.set_footer(text='Plyoox Logging', icon_url=self.bot.user.avatar_url)

        if data['id'] and data['token']:
            try:
                webhook = discord.Webhook.partial(data['id'], data['token'], adapter=discord.RequestsWebhookAdapter())
                # noinspection PyAsyncCall
                webhook.send(embed=embed, username=self.bot.user.name, avatar_url=self.bot.user.avatar_url)
            except discord.NotFound:
                await self.createWebhook(user.guild.id)
Example #4
0
    def send_ads(self, ad_dict, discord_title, colour_flag, **kwargs):
        global webhook_cache

        if not "webhook_cache" in globals():
            webhook_cache = {}

        webhook_url = kwargs["webhook"]
        self.bot_name = kwargs["botname"]
        self.avatar = kwargs["avatar"]

        if not webhook_url in webhook_cache:
            webhook_cache[webhook_url] = discord.Webhook.from_url(
                webhook_url, adapter=discord.RequestsWebhookAdapter())

        self.webhook = webhook_cache[webhook_url]

        title = self.__create_discord_title(discord_title, len(ad_dict))

        self.webhook.send(content=f"**{title}**",
                          username=self.bot_name,
                          avatar_url=self.avatar)

        for ad_id in ad_dict:
            embed = self.__create_discord_embed(ad_dict, ad_id, colour_flag)

            self.webhook.send(embed=embed,
                              username=self.bot_name,
                              avatar_url=self.avatar)
Example #5
0
 async def sub(self, ctx, *args):
     if len(args) == 0 or 'help' in ''.join(args).lower():
         embed = discord.Embed(
             title='Get development updates and/or events in your server!',
             description=
             'Want to get up-to-date development updates? either it is bugfixes, cool events, etc.\nHow do you set up? Use `{}sub <discord webhook url>`.\nIf you still do not understand, [please watch the tutorial video here.](https://vierofernando.is-inside.me/fEhT86EE.mp4)'
             .format(ctx.bot.command_prefix),
             color=ctx.guild.me.roles[::-1][0].color)
         return await ctx.send(embed=embed)
     elif 'reset' in ''.join(args).lower():
         ctx.bot.db.Dashboard.subscribe(None, ctx.guild.id, reset=True)
         return await ctx.send('{} | Subscription has been deleted.'.format(
             ctx.bot.success_emoji))
     url = args[0].replace('<', '').replace('>', '')
     try:
         web = discord.Webhook.from_url(
             url, adapter=discord.RequestsWebhookAdapter())
     except:
         raise ctx.bot.utils.send_error_message(
             "Invalid Webhook URL. Please send the one according to the tutorial."
         )
     ctx.bot.db.Dashboard.subscribe(url, ctx.guild.id)
     await ctx.message.add_reaction(ctx.bot.success_emoji)
     web.send(embed=discord.Embed(
         title=f'Congratulations, {str(ctx.author)}!',
         description=
         'Your webhook is now set! ;)\nNow every development updates or username601 events will be set here.\n\nIf you change your mind, you can do `{}sub reset` to remove the webhook from the database.\n[Join our support server if you still have any questions.]({})'
         .format(ctx.bot.command_prefix,
                 ctx.bot.utils.config('SERVER_INVITE')),
         color=discord.Color.green()),
              username='******',
              avatar_url=ctx.bot.user.avatar_url)
Example #6
0
 def __init__(self):
     self.start_time = datetime.datetime.now()
     self.prefixes = get_all_prefixes()
     super().__init__(command_prefix=get_prefix, case_insensitive=True)
     self.token = 'no u'  # yes this is a necessary change
     self.version = config.version
     self.version_info = config.version_description
     self.remove_command('help')
     self.weeb = weeb.Client(token=config.weeb_token,
                             user_agent='Godavaru/' + self.version + '/' +
                             config.environment)
     self.seen_messages = 0
     self.reconnects = 0
     self.executed_commands = 0
     self.webhook = discord.Webhook.partial(
         int(config.webhook_id),
         config.webhook_token,
         adapter=discord.RequestsWebhookAdapter())
     self.logger = logging.getLogger(__name__)
     self.logger.info('Starting initial bot startup...')
     for extension in initial_extensions:
         try:
             self.load_extension(extension)
         except Exception:
             print(f'Failed to load extension {extension}.')
             print(traceback.format_exc())
Example #7
0
def flaskbb_event_topic_save_after(topic, is_new):
    if "SENAT_FORUM_ID" not in current_app.config or "SENAT_JOURNAL_WEBHOOK" not in current_app.config:
        print("SENAT_JOURNAL isn't configured")
        return

    if not is_new:
        return

    if topic.forum_id == current_app.config["SENAT_FORUM_ID"]:
        try:
            webhook = discord.Webhook.from_url(
                current_app.config["SENAT_JOURNAL_WEBHOOK"],
                adapter=discord.RequestsWebhookAdapter())

            desc = topic.first_post.content
            desc = (desc[:2000] + "\n...") if len(desc) > 2000 else desc

            url = url_for("forum.view_topic",
                          topic_id=topic.id,
                          slug=topic.slug,
                          _external=True)
            embed = discord.Embed(title=topic.title, description=desc, url=url)
            embed.add_field(name="Author:", value=topic.user.display_name)

            webhook.send(embed=embed)
        except Exception:
            print(traceback.format_exc())
def start_ensemble_with_progressbar(total,
                                    desc,
                                    webhook_url,
                                    fname_counter,
                                    ensembleproblem,
                                    save_everystep=True):
    webhook = discord.Webhook.from_url(
        webhook_url, adapter=discord.RequestsWebhookAdapter())
    pbar_str = Array(ctypes.c_wchar, " " * 60)
    msg_id = Value(ctypes.c_longlong, 0)
    time.sleep(0.1)
    pthread = Process(target=discord_progressbar,
                      args=(pbar_str, webhook_url, msg_id, fname_counter,
                            total, desc))
    pthread.start()

    run_simulation(fname_counter, total, ensembleproblem, save_everystep)

    pthread.join()

    embed = create_pbar_discord_embed("", desc)
    embed_dict = embed.to_dict()
    embed_dict['fields'][0]['value'] = pbar_str[:]
    embed = discord.Embed.from_dict(embed_dict)
    embed.color = C3
    embed.title = embed.title.replace("Running", "Completed")
    webhook.delete_message(message_id=msg_id.value)
    webhook.send(embed=embed)
Example #9
0
    def send_alert(self):
        # Create webhook
        webhook = discord.Webhook.partial(
            os.getenv("DISCORD_WEBHOOK_ID"),
            os.getenv("DISCORD_WEBHOOK_TOKEN"),
            adapter=discord.RequestsWebhookAdapter())

        date_time_str = datetime.datetime.now()
        if type(date_time_str) == str:
            date_time_obj = datetime.strptime(date_time_str,
                                              "%Y-%m-%dT%H:%M:%S.%f%z")
        else:
            date_time_obj = date_time_str

        # Build the embed
        embed = discord.Embed(title=self.name,
                              description=self.description,
                              color=0x00ff00)
        # embed.add_field(name='Description', value=self.description, inline=True)
        embed.add_field(name='Price', value='£' + self.price, inline=True)
        embed.add_field(name='Type', value=self.listing_type, inline=True)
        embed.add_field(name=":date: Time of Alert",
                        value=date_time_obj.strftime("%d/%m/%Y  %H:%M %Z"),
                        inline=True)
        embed.add_field(name=':date: Start Time',
                        value=self.start_time.strftime("%d/%m/%Y  %H:%M %Z"),
                        inline=True)
        embed.add_field(name=':date: End Time',
                        value=self.end_time.strftime("%d/%m/%Y  %H:%M %Z"),
                        inline=True)
        embed.add_field(name='URL', value=self.url, inline=True)
        embed.set_image(url=self.image)

        # Send it
        webhook.send(embed=embed)
Example #10
0
    async def on_member_join(self, user: discord.Member):
        data = await self.bot.db.fetchrow(
            'SELECT l.id, l.token, l.memberjoin, m.logging FROM config.logging l INNER JOIN config.modules m ON l.sid = m.sid WHERE l.sid = $1',
            user.guild.id)
        if not data or not data['logging'] or not data['memberjoin']:
            return

        days_dc = (datetime.datetime.now() - user.created_at).days
        embed = discord.Embed(color=std.normal_color, title='LOGGING [JOIN]')
        embed.set_thumbnail(url=user.avatar_url)
        embed.timestamp = datetime.datetime.utcnow()
        embed.description = f'{std.inbox_emoji} {user} ist dem Discord gejoint.'
        embed.add_field(name=f'{std.info_emoji} **__User__**',
                        value=f'{std.nametag_emoji} {user}\n'
                              f'{std.botdev_emoji} {user.id}\n'
                              f'{std.mention_emoji} {user.mention}',
                        inline=False)
        embed.add_field(name=f'{std.date_emoji} Account-Alter', value=str(days_dc), inline=False)
        embed.timestamp = datetime.datetime.utcnow()
        embed.set_footer(text='Plyoox Logging', icon_url=self.bot.user.avatar_url)

        if data['id'] and data['token']:
            try:
                webhook = discord.Webhook.partial(data['id'], data['token'], adapter=discord.RequestsWebhookAdapter())
                # noinspection PyAsyncCall
                webhook.send(embed=embed, username=self.bot.user.name, avatar_url=self.bot.user.avatar_url)
            except discord.NotFound:
                await self.createWebhook(user.guild.id)
Example #11
0
def setup_logging(bot):
    logging.getLogger('discord').setLevel(logging.INFO)
    logging.getLogger('discord.http').setLevel(logging.WARNING)
    logging.getLogger('discord.state').setLevel(logging.WARNING)
    logging.getLogger('websockets.protocol').setLevel(logging.WARNING)
    logging.getLogger('coc').setLevel(logging.INFO)
    logging.getLogger('coc.http').setLevel(logging.WARNING)

    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    handler = logging.FileHandler(filename='donationtracker.log',
                                  encoding='utf-8',
                                  mode='w')
    handler.setLevel(logging.INFO)
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    dt_fmt = '%d-%m-%Y %H:%M:%S'
    fmt = logging.Formatter('[{asctime}] [{levelname:<7}] {name}: {message}',
                            dt_fmt,
                            style='{')
    handler.setFormatter(fmt)
    stream_handler.setFormatter(handler)
    log.addHandler(handler)
    log.addHandler(stream_handler)

    error_webhook = discord.Webhook.partial(
        id=creds.log_hook_id,
        token=creds.log_hook_token,
        adapter=discord.AsyncWebhookAdapter(session=bot.session))
    requests_hook = discord.Webhook.partial(
        id=creds.log_hook_id,
        token=creds.log_hook_token,
        adapter=discord.RequestsWebhookAdapter())

    class DiscordHandler(logging.NullHandler):
        def handle(self, record):
            if not creds.live:
                return
            if record.levelno < 20:
                return

            to_send = fmt.format(record)

            messages = []
            for i in range(math.ceil(len(to_send) / 1950)):
                messages.append(to_send[i * 1950:(i + 1) * 1950])

            for n in messages:
                try:
                    asyncio.ensure_future(error_webhook.send(f'```\n{n}\n```'))
                except:
                    requests_hook.send(f'```\n{n}\n```')

        def emit(self, record):
            self.handle(record)

    discord_hndlr = DiscordHandler()
    discord_hndlr.setLevel(logging.DEBUG)
    log.addHandler(discord_hndlr)
Example #12
0
 async def on_ready(self):
     print(f"Ready: {self.bot.user} | Guilds: {len(self.bot.guilds)}")
     await self.bot.change_presence(
         activity=discord.Game(type=0,
                               name="Enjoying V3 | owo announcement"),
         status=discord.Status.online,
     )
     self.bot.webhook = discord.Webhook.from_url(
         self.bot.config.webhook, adapter=discord.RequestsWebhookAdapter())
     self.bot.webhook.send(f"*`[i]`* **{self.bot.user} is ready.**")
Example #13
0
    async def on_ready(self):
        with open(json_location) as creds:
            self.bot.loaded = json.load(creds)
        self.bot.coc = self.get_coc()
        webid = self.bot.loaded['awspamhookid']
        webtoken = self.bot.loaded['awspamhooktoken']
        self.bot.awwebhook = discord.Webhook.partial(
            id=webid, token=webtoken, adapter=discord.RequestsWebhookAdapter())

        print('Ready')
Example #14
0
async def webhook_imitate(message: str,
                          user: discord.User,
                          channel: discord.TextChannel,
                          file: discord.File = None):
    hook = discord.Webhook.from_url(await get_hook_url(channel),
                                    adapter=discord.RequestsWebhookAdapter())
    try:
        hook.send(content=message,
                  wait=False,
                  username=str(user.display_name),
                  avatar_url=str(user.avatar_url),
                  file=file)
    except Exception as e:
        print(e, ", creating new webhook")
        await database.new_webhook(channel)
        hook = discord.Webhook.from_url(
            await get_hook_url(channel),
            adapter=discord.RequestsWebhookAdapter())
        hook.send(content=message,
                  wait=False,
                  username=str(user.display_name),
                  avatar_url=str(user.avatar_url),
                  file=file)
def discord_progressbar(pbar_str,
                        webhook_url,
                        msg_id,
                        fname_counter,
                        total,
                        desc=None,
                        dt=2):
    pbar, embed = create_pbar_discord(total, desc)
    webhook = discord.Webhook.from_url(
        webhook_url, adapter=discord.RequestsWebhookAdapter())
    msg = webhook.send(embed=embed, wait=True)
    msg_id.value = msg.id
    embed_dict = embed.to_dict()
    while True:
        try:
            with open(fname_counter, 'r') as f:
                for line in f:
                    pass
                cnt = int(line.strip('\n'))
        except Exception as e:
            raise e
        try:
            webhook = discord.Webhook.from_url(
                webhook_url, adapter=discord.RequestsWebhookAdapter())
            if (cnt != pbar.n) or (cnt == 0):
                pbar.n = cnt
                embed_dict['fields'][0]['value'] = str(pbar)
                webhook.edit_message(message_id=msg_id.value,
                                     embed=discord.Embed.from_dict(embed_dict))
                pbar_str[:len(str(pbar))] = str(pbar)
                if pbar.n >= pbar.total:
                    break
            time.sleep(dt)
        except Exception as e:
            time.sleep(dt)
            logging.warning(e)
            pass
Example #16
0
 async def send_as(self, message, channel, ID, *arg, **kwargs):
     user = self.get_user(ID)
     try:
         if not user:
             user = await self.fetch_user(ID)
         URL = WEBHOOKS[channel.id]
     except:
         return await channel.send(message, *arg, **kwargs)
     webhook = discord.Webhook.from_url(
         URL, adapter=discord.RequestsWebhookAdapter())
     webhook.send(message,
                  *arg,
                  username=user.display_name + " (CathoLingo)",
                  avatar_url=user.avatar_url,
                  **kwargs)
Example #17
0
    def post_webhook(self):
        """discord.Webhook: The webhook to send new posts through."""
        if self._post_webhook is None:
            url = self.config.post_webhook
            adapter = discord.RequestsWebhookAdapter()

            try:
                self._post_webhook = discord.Webhook.from_url(url,
                                                              adapter=adapter)
            except Exception as e:
                self.logger.exception("Could not create post webhook!",
                                      exc_info=e)
                sys.exit(1)

        return self._post_webhook
def send_discord(file, message, ttime):
    webhook = discord.Webhook.from_url(
        url, adapter=discord.RequestsWebhookAdapter())
    e = discord.Embed(description=ttime)
    if file:
        with open(file, "rb") as f:
            my_file = discord.File(f)
        webhook.send(message,
                     username='******',
                     file=my_file,
                     embed=e)
    elif message:
        webhook.send(message, username='******', embed=e)
    else:
        return False
Example #19
0
    def __init__(self):
        super().__init__(command_prefix="cc!",
                         case_insensitive=True,
                         allowed_mentions=AllowedMentions.none(),
                         intents=INTENTS,
                         activity=discord.Activity(
                             type=discord.ActivityType.watching,
                             name="People play CircuitCraft"))

        self.logging_hook = discord.Webhook.from_url(
            os.getenv("WEBHOOK"), adapter=discord.RequestsWebhookAdapter())

        self.mc = McClient("~/circuitcraft", "[CircuitCraft] ", self)
        self.rc = McClient("~/verifycraft", "[Verification] ", self)
        self.db = Database()
Example #20
0
    async def on_raw_message_edit(self, payload):
        if not payload.data or 'content' not in payload.data or 'guild_id' not in payload.data:
            return

        data = await self.bot.db.fetchrow(
            'SELECT l.id, l.token, l.msgedit, m.logging FROM config.logging l INNER JOIN config.modules m ON l.sid = m.sid WHERE l.sid = $1',
            int(payload.data['guild_id']))
        if not data or not data['logging'] or not data['msgedit']:
            return

        msgData = payload.data
        if 'author' not in msgData:
            return
        user = msgData['author']
        embed = discord.Embed(color=std.normal_color, title='LOGGING [MESSAGE EDIT]')
        embed.timestamp = datetime.datetime.utcnow()
        embed.set_footer(text='Plyoox Logging', icon_url=self.bot.user.avatar_url)
        msg: discord.Message = payload.cached_message
        embed.description = f'[Springe zur Nachricht](https://discord.com/channels/{msgData["guild_id"]}/{payload.channel_id}/{payload.message_id})'
        embed.add_field(name=f'{std.info_emoji} **__User__**',
                        value=f'{std.nametag_emoji} {user["username"]}#{user["discriminator"]}\n'
                              f'{std.botdev_emoji} {user["id"]}\n'
                              f'{std.mention_emoji} <@{user["id"]}>',
                        inline=False)

        if msg is None:
            if not msgData['content']:
                return
            embed.add_field(name=f'{std.richPresence_emoji} **__Neue Nachricht__**',
                            value=msgData['content'])
        else:
            if msgData['content'] and msg.content is not None:
                if msgData['content'] == msg.content:
                    return
                embed.add_field(name=f'{std.richPresence_emoji} **__Neue Nachricht__**',
                                value=msgData['content'], inline=False)
                embed.add_field(name=f'{std.richPresence_emoji} **__Alte Nachricht__**',
                                value=msg.content, inline=False)
            else:
                return

        if data['id'] and data['token']:
            try:
                webhook = discord.Webhook.partial(data['id'], data['token'], adapter=discord.RequestsWebhookAdapter())
                # noinspection PyAsyncCall
                webhook.send(embed=embed, username=self.bot.user.name, avatar_url=self.bot.user.avatar_url)
            except discord.NotFound:
                await self.createWebhook(int(payload.data['guild_id']))
    def __init__(self, webhook_url: str):
        """Creates a Grinch from a Discord Webhook URL

        Args:
            webhook_url (str): The webhook URL.
        """
        # We create our own Webhook object from a URL instead of passing
        # objects around due to issues with synchronous vs asynchronous
        # webhook adapters.

        # TODO: Implement error handling
        self.webhook = discord.Webhook.from_url(
            webhook_url, adapter=discord.RequestsWebhookAdapter())

        self.name = getenv('WEBHOOK_NAME')
        self.avatar_url = getenv('WEBHOOK_AVATAR_URL')
Example #22
0
    def error_webhook(self):
        """Optional[discord.Webhook]: Webhook to send errors through."""
        if self.config.error_webhook is None:
            return None

        if self._error_webhook is None:
            url = self.config.error_webhook
            adapter = discord.RequestsWebhookAdapter()
            try:
                self._error_webhook = discord.Webhook.from_url(url,
                                                               adapter=adapter)
            except Exception as e:
                self.logger.exception("Could not create error webhook!",
                                      exc_info=e)
                sys.exit(1)

        return self._error_webhook
 async def send_log(self, record: logging.LogRecord):
     self.format(record)
     embed = discord.Embed(title=record.levelname,
                           description=f'```{record.message}```',
                           timestamp=datetime.strptime(
                               record.asctime[:-4], '%Y-%m-%d %H:%M:%S'))
     embed.add_field(name='Module',
                     value=f'`{record.name}`: `{record.module}`')
     try:
         webhook = discord.Webhook.from_url(
             keys.logWebhook,
             adapter=discord.AsyncWebhookAdapter(self.client_session))
         await webhook.send(embed=embed)
     except (RuntimeError, BaseException):
         webhook = discord.Webhook.from_url(
             keys.logWebhook, adapter=discord.RequestsWebhookAdapter())
         webhook.send(embed=embed)
Example #24
0
    def is_property_valid(self, key, value):
        if key == "webhook":
            try:
                discord.Webhook.from_url(
                    value, adapter=discord.RequestsWebhookAdapter())
                return True, None
            except:
                return False, "Webhook is invalid"
        elif key == "botname":
            if value == "" or value is None:
                return False, "Botname cannot be empty"
            else:
                return True, None
        else:
            raise ValueError(f"Invalid property: {key}")

        return False
Example #25
0
    def send(self, title, message, **kwargs):
        global webhook_cache

        if not "webhook_cache" in globals():
            webhook_cache = {}

        webhook_url = kwargs["webhook"]
        self.bot_name = kwargs["botname"]

        if not webhook_url in webhook_cache:
            webhook_cache[webhook_url] = discord.Webhook.from_url(
                webhook_url, adapter=discord.RequestsWebhookAdapter())

        self.webhook = webhook_cache[webhook_url]

        self.webhook.send(content=f"**{title}**", username=self.bot_name)
        self.webhook.send(content=message, username=self.bot_name)
Example #26
0
def signUp(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('dashboard')

    data = University.objects.all()

    if request.method == "POST":
        name = request.POST['name']
        email = request.POST['email']
        phoneNum = request.POST['phoneNumber']
        print("HELLO!")
        form = UserForm(data = request.POST)
        print(form)
        if form.is_valid():
            user = form.save()
            print("gets here")

            user.is_active = False
            user.save()

            # uniqueURL = URLCalendar(calendar=urlGenerator.createURL(name, email))
            # uniqueURL.save()
            uniqueURL = urlGenerator.createURL(name, email)
            # print("Unique URL is " + uniqueURL)
            newStudent = Student(name=name, email=email, phone_num=phoneNum, calendar_link=uniqueURL)
            newStudent.save()

            print("Saved student object")
            
            # https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook
            webhookURL = os.getenv("WEBHOOK_URL")
            webhook = discord.Webhook.from_url(webhookURL, adapter=discord.RequestsWebhookAdapter())
            embed = discord.Embed(title="New User", description="A new user has registered with CourseCal!", colour=0x47ff8e)
            embed.add_field(name="Name", value=name)
            embed.add_field(name="Email", value=email)
            embed.add_field(name="Calendar ID", value=uniqueURL)
            webhook.send(embed=embed)

            html_msg = f"<p><a href='{request.build_absolute_uri('/register/confirm/')}{user.id}'>Click here to activate your account!</a></p>"
            mail.send_mail("Account Confirmation", "Please confirm your account registration.", settings.EMAIL_HOST_USER, [user.email], html_message=html_msg)
            return render(request, 'sign-up.html', {"success":"Check your email, I sent you an account confirmation link!", "universities": data})
        else:
            return render(request, 'sign-up.html', {"error": "Error: There was a form error. Retype the above information and resubmit!", "universities": data})
    return render(request, 'sign-up.html', {"universities": data})
Example #27
0
    def __init__(self, webhook: Union[discord.Webhook, str], name: str,
                 avatar_url: str):
        """Wrapper class for webhook logic that powers the Grinch's messages.

        Args:
            webhook (discord.Webhook): The Webhook for sending messages.
            name (str): The display name of the Webhook
            avatar_url (str): The URL of the Webhook's avatar.
        """
        # TODO: Persist webhook URL in the database, restore it when needed

        if isinstance(webhook, discord.Webhook):
            self.webhook = webhook
        else:
            self.webhook = discord.Webhook.from_url(
                webhook, adapter=discord.RequestsWebhookAdapter())

        self.name = name
        self.avatar_url = avatar_url
Example #28
0
def sendPlayerMsg(pseudo, msg):

    print("[INFO] say on discord : <" + pseudo + "> " + msg)

    webhook = discord.Webhook.from_url(
        config.webhookURL, adapter=discord.RequestsWebhookAdapter())

    defaultHeadURL = "https://i.imgur.com/kHXRnzX.png"  # steve head

    playersDBFile = open('playersDB.json', 'r')
    playersDB = json.loads(playersDBFile.read())
    playersDBFile.close()

    for playerData in playersDB:
        if playerData['minecraft-pseudo'] == pseudo:
            if playerData['minecraft-head-url'] != "":
                defaultHeadURL = playerData['minecraft-head-url']

    webhook.send(msg, username=pseudo, avatar_url=defaultHeadURL)
Example #29
0
    def push_log_message(p, m, post, color):
        message = m if m != "" else p
        prefix = p if m != "" else "Log"

        logger = logging.getLogger("Logger")
        logger.setLevel(logging.DEBUG)

        fh = logging.FileHandler('output.log', mode='a')
        fh.setLevel(logging.DEBUG)
        logger.addHandler(fh)

        ch = logging.StreamHandler(stream=sys.stdout)
        ch.setLevel(logging.INFO)
        logger.addHandler(ch)

        logger.info("[{}]: {}".format(prefix, message))

        logger.handlers = []

        if sys.platform == "linux" and post:
            try:
                url = ApiKeys.get_log_webhook()
                if prefix == "Info" or prefix == "Alerts":
                    url = ApiKeys.get_log_webhook(mode="quiet")
                elif prefix == "Status":
                    color = 0x03A9F4
                elif prefix == "Exchange":
                    color = 0xFFC107
                elif prefix == "Warning":
                    color = 0xFF9800
                elif prefix == "Error":
                    color = 0xFF5722
                elif prefix == "Fatal error":
                    color = 0xF44336

                logWebhook = discord.Webhook.from_url(
                    url, adapter=discord.RequestsWebhookAdapter())
                logEmbed = discord.Embed(description=message, color=color)
                logEmbed.set_footer(text=Utils.get_current_date())
                logWebhook.send(embed=logEmbed, username='******')
            except:
                pass
Example #30
0
 async def announce(self, ctx, *args):
     if ctx.author.id not in [661200758510977084, 766952708602331137]: return
     await ctx.message.add_reaction(ctx.bot.loading_emoji)
     data, wr, sc = ctx.bot.db.Dashboard.get_subscribers(), 0, 0
     for i in data:
         try:
             web = discord.Webhook.from_url(
                 i['url'], adapter=discord.RequestsWebhookAdapter()
             )
             web.send(
                 embed=discord.Embed(title=f'Username601 News: {str(t.now())[:-7]}', description=' '.join(args).replace('\\n', '\n'), color=discord.Color.green()),
                 username='******',
                 avatar_url=ctx.bot.user.avatar_url
             )
             sc += 1
         except:
             wr += 1
             ctx.bot.db.Dashboard.subscribe(None, i['serverid'], reset=True)
         await sleep(1)
     await ctx.send(f'Done with {sc} success and {wr} fails')