Esempio n. 1
0
async def SDSUpdate(request):
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(webhook_url, adapter=AsyncWebhookAdapter(session)) 
        if not request.match_info:
            return web.Response(status=400)
        await webhook.send(request.match_info['SDSUpdate'])
        return web.Response(text="sent successfully")
Esempio n. 2
0
async def on_ready():
    """Async setup function for the bot"""
    if hasattr(bot, "ready_time"):
        return
    bot.ready_time = dt.utcnow()
    bot.logger.info("Bot ready - {0.name!r} ({0.id}). Loaded in {1}".format(
        bot.user, bot.uptime))

    # Update env on site
    env = jinja_env(site)
    env.globals.update(aidzman=bot.get_user(bot.owner_id))

    # Update oauth stuff for the website
    site.oauth_data = {
        "client_id": bot.user.id,
        "client_secret": bot.env["BOT_CLIENT_SECRET"],
        "redirect_uri": bot.oauth_callback,
    }
    site.oauth_url = "https://discordapp.com/api/oauth2/authorize?" + urlencode(
        {
            "client_id": bot.user.id,
            "redirect_uri": bot.oauth_callback,
            "response_type": "code",
            "scope": "identify guilds",
        })

    # Announce our presence to the whole wide world
    webhook = Webhook.from_url(bot.env["COMMANDS_WEBHOOK_URL"],
                               adapter=AsyncWebhookAdapter(bot.session))
    e = Embed(colour=0x00B7D9,
              timestamp=dt.utcnow(),
              description=f"Time taken to load: `{bot.uptime}`")

    e.set_footer(text=bot.user)
    e.set_author(name="Bot restarted", icon_url="https://bit.ly/2Sd33Wx")
    await webhook.send(embed=e,
                       username=bot.user.name,
                       avatar_url=bot.user.avatar_url)
Esempio n. 3
0
    async def parse_at_someone_0(self, data):
        guild_id = data["guild_id"]
        channel_id = data["channel_id"]
        webhook_url = await self.get_webhook(guild_id, channel_id)
        if webhook_url is None:
            return

        async with ClientSession() as client:
            webhook = Webhook.from_url(webhook_url, adapter=AsyncWebhookAdapter(client))
            user_id = await self.get_random_user(guild_id)
            author = data["author"]
            avatar = author["avatar"]
            if avatar:
                avatar = f"https://cdn.discordapp.com/avatars/{author['user_id']}/{avatar}.png?size=256"
            else:
                avatar = f"https://cdn.discordapp.com/embed/avatars/{int(author['discriminator']) % 5}.png"

            await webhook.send(
                content=f"**@someone {random.choice(responses)} (<@{user_id}>)**",
                username=data["nickname"] or author["username"],
                avatar_url=avatar,
                allowed_mentions=AllowedMentions(users=False)
            )
Esempio n. 4
0
def send_webhook():
    url = ''
    webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter())
    embed = Embed(
        title='Success - kith.com',
        url=
        'https://cdn.shopify.com/s/files/1/0094/2252/products/KH3605-104_063.progressive.jpg?v=1571984567'
    )
    embed.add_field(name='Size', value='L', inline=True)
    embed.add_field(name='Product', value='KITH LAX L/S TEE', inline=True)
    embed.add_field(name='Delay', value='1000', inline=True)
    embed.add_field(name='Profile', value='||test||', inline=False)
    embed.add_field(name='Tasks', value='15', inline=False)
    embed.set_footer(text='Balkobot', icon_url=icon_url())
    embed.set_thumbnail(
        url=
        'https://cdn.shopify.com/s/files/1/0094/2252/products/KH3605-104_063.progressive.jpg?v=1571984567'
    )
    webhook.send(
        embed=embed,
        avatar_url=avatar_url(),
        username='******',
    )
Esempio n. 5
0
    async def on_member_join(self, userObj: discord.Member) -> None:
        # Ignore if it's a bot
        if userObj.bot:
            return

        # Ignore if hellohook is disabled in the user's guild
        userGuild = userObj.guild
        hellohookEnabled = await self.config.guild(userGuild
                                                   ).hellohookEnabled()
        if hellohookEnabled == False:
            return

        greetMessage = await self.config.guild(userGuild).greetMessage()
        if not greetMessage:
            updatev1data = await self.updatev1data(userObj.guild)
            if updatev1data == False:
                return
        greetWebhook = await self.config.guild(userGuild).greetWebhook()
        async with aiohttp.ClientSession() as session:
            webhook = Webhook.from_url(greetWebhook,
                                       adapter=AsyncWebhookAdapter(session))
            await self.hellohookSender(webhook, userObj)
        return
Esempio n. 6
0
def send_webhook():
    url = ''

    webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter())
    content = "Success: adidas Originals Yeezy Boost 350 V2 - Men's"

    embed = Embed(title='You cooked', color=Color.from_rgb(155, 89, 182))

    embed.set_thumbnail(
        url=
        'https://images-ext-1.discordapp.net/external/slLUJkwr81yr4FTh19TyyD-D7_-xNVihD19n45AeZwY/https/images.footlocker.com/pi/9033FL/cart/9033FL.jpeg'
    )
    embed.add_field(name='Website',value='Footlocker.com')\
    .add_field(name='Product',value='adidas Originals Yeezy Boost 350 V2 - Men\'s')\
    .add_field(name='Size',value='||10||')\
    .add_field(name='Price',value='$220.00')\
    .add_field(name='Link',value='9033FL')\
    .add_field(name='Profile',value='||Test||')\
    .add_field(name='Proxy',value='||TCB||')\
    .add_field(name='Time Stamp(utc)',value='2020-02-23 01:10:32AM')\
    .add_field(name='Mode',value='Safe')

    webhook.send(content, embed=embed)
Esempio n. 7
0
def send_webhook(
    bot,
    product,
    size,
    category,
    color,
    profile,
    thumbnail,
    webhook,
    webhook_author='Spidey Bot',
    webhook_avatar='https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png'
):
    #url = 'https://ptb.discordapp.com/api/webhooks/699263716859969586/o1YEjsT2aQtgG0NGgfHgaVxTkL9sVttTYLBKJ_hQt9ey5NSTRVnu0yrggHOK2YdpMN8q'
    webhook = Webhook.from_url(webhook, adapter=RequestsWebhookAdapter())
    if bot == 'cyber':
        embed = send_cyber(product, size, profile, category, color, thumbnail)
    elif bot == 'kodai':
        embed = send_kodai(product, size, color, profile, thumbnail)
    elif bot == 'balko':
        embed = send_balko(product, size, profile, thumbnail)
    webhook.send(embed=embed,
                 avatar_url=webhook_avatar,
                 username=webhook_author)
Esempio n. 8
0
async def sendWebhook(region, rewardId, questId, endTimestamp):
    print('New quest found ({0}), sending Webhook'.format(questId))

    # Fetch Webhook URL
    webhookurl = ''
    with open('webhook.py') as file:
        webhookurl = file.read()

    # Calculate time until the quest goes away
    start = datetime.now()
    end = datetime.fromtimestamp(endTimestamp / 1e3)
    duration = end - start

    faction = 'Army of the Light' if rewardId == 152957 else 'Argussian Reach'
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('{0}'.format(webhookurl),
                                   adapter=AsyncWebhookAdapter(session))
        await webhook.send(
            '<@118461244784115713>\n{0} - {1} Reputation - Ends in {3} Hours and {4} minutes\nQuest: http://www.wowhead.com/quest={2}'
            .format(region, faction, questId, duration.seconds // 3600,
                    (duration.seconds // 60) % 60),
            username='******',
            avatar_url='https://i.imgur.com/XKQ9yMd.png')
Esempio n. 9
0
def send_webhook():
    url = 'webhook'
    webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter())

    embed = Embed(title='Yeezy 700 V3"Alvah"',
                  url="https://twitter.com/orbitboteu",
                  color=Color.from_rgb(67, 194, 122))

    embed.set_thumbnail(url=product_url())

    embed.add_field(name="Srore", value="Holypopstore")\
        .add_field(name="profile", value="||test||")\
        .add_field(name="size", value="9")
    embed.add_field(name="Payment Method", value="Paypal")\
        .add_field(name="Account", value="||[email protected]||")\
        .add_field(name="Timestamp", value="||2020-03-31 13:00:16PM(UTC)||", inline=False)
    embed.set_footer(text='Orbit', icon_url=avatar_url())

    embed.set_author(name="Successfully checked out!")

    webhook.send(embed=embed,
                 avatar_url=avatar_url(),
                 username="******")
Esempio n. 10
0
class Announcer:

    cMention = ''
    cMessage = ''
    webhook = Webhook.from_url(
        'https://discordapp.com/api/webhooks/790274622880612393/cflyX0RGsh5kqkz5x2LRqe6cJZpSt7dH6RY5-PvQKSrOP5720qTkoEbIJY9DPkT_Y69T',
        adapter=RequestsWebhookAdapter())

    def __init__(self, mention=None, message=None):
        self.cMention = mention
        self.cMessage = message

    def announce(self):
        msg = 'This is an announcement for => ' + self.cMention + '\n' + self.cMessage
        self.webhook.send(msg)

    def notify_acceptance(self, username):
        msg = f'{username} is accepted into the club.'
        self.webhook.send(msg)

    def add_role(self, username):
        msg = f'jillu admit <@{username}>'
        self.webhook.send(msg)
Esempio n. 11
0
    async def spotifyembed(self, ctx, spotifyLink, asMyself: bool = False):
        """Return a Spotify embed link
        
        Can set asMyself to true/false, for sending as webhook
        
        *Admins: To edit auto-reply and other settings, use  `[p]setspotifyembed`*"""
        spembedSplit = spotifyLink.split('.com/')
        sendMsg = spembedSplit[0] + ".com/embed/" + spembedSplit[1]

        if asMyself == False:
            return await ctx.send(sendMsg)
        elif asMyself == True:
            # Find a webhook that the bot made
            try:
                whooklist = await ctx.channel.webhooks()
                whurl = ""
                # Return if match
                for wh in whooklist:
                    if self.bot.user == wh.user:
                        whurl = wh.url
                # Make new webhook if one didn't exist
                if whurl == "":
                    newHook = await ctx.channel.create_webhook(name="Webhook")
                    whurl = newHook.url

                async with aiohttp.ClientSession() as session:
                    webhook = Webhook.from_url(
                        whurl, adapter=AsyncWebhookAdapter(session))
                    await webhook.send(
                        sendMsg,
                        username=ctx.author.display_name,
                        avatar_url=ctx.author.avatar_url,
                    )
            except discord.errors.Forbidden:
                return await ctx.send(sendMsg)
        else:
            return await ctx.send("An error occurred.")
Esempio n. 12
0
def alert(name, status, link, log):
    # Get the time and format it.
    time_stamp = str((datetime.now()).strftime("%H:%M:%S"))
    # Output current status and update.
    log.write("[" + time_stamp + "] >>> Status for " + name +
              " changed! New status: " + status + "\n" + "[" + time_stamp +
              "] >>> Retailer link: " + link + "\n")
    log.flush()

    # If discord is enabled, notify discord.
    if config['discord']['enabled'] == True:
        # Get discord configuration.
        discord_cfg = config['discord']

        # Create the message for the notification.
        message = ("**" + name + " status changed! " + " <@&" +
                   str(discord_cfg['roleID']) + ">**\n" + ">>> New status: `" +
                   status + "`\n" + "Retailer link: " + link)

        # Create webhook and send the message.
        webhook = Webhook.from_url(discord_cfg['webhookUrl'],
                                   adapter=RequestsWebhookAdapter())
        webhook.send(message)

    # If Windows 10 toast is enabled, create a toast notification.
    if config['win10toast']['enabled'] == True:
        # Get win10toast configuration.
        icon_file = os.path.abspath(config['win10toast']['icon'])

        # Show toast notification.
        toaster = ToastNotifier()
        toaster.show_toast(name + "status changed",
                           "New status: '" + status + "'\n" +
                           " Retailer link: " + link,
                           icon_path=icon_file,
                           duration=5,
                           threaded=True)
Esempio n. 13
0
async def chat(uid, secret, hooks, room):

    uri = f"wss://ws-chat.torn.com/chat/ws?uid={iud}&secret={secret}"

    token, agent = cloudscraper.get_cookie_string("https://www.torn.com")
    headers = {"User-Agent": agent, "Cookie": token}

    async with websockets.connect(uri, origin="https://www.torn.com", extra_headers=headers) as websocket:
        async with aiohttp.ClientSession() as session:
            webhooks = dict({})
            for hookId, hookurl in hooks.items():
                webhooks[hookId] = Webhook.from_url(hookurl, adapter=AsyncWebhookAdapter(session))

            while(True):
                data = await websocket.recv()
                d = json.loads(data).get("data", [dict({})])[0]
                txt = d.get("messageText")
                if d.get("roomId", "") == room and txt:
                    msg = chat_message(d)
                    await webhooks["full"].send(msg)

                    for keyword in [k for k in webhooks if k != "full"]:
                        if re.search(f"\W*({keyword})\W*", txt.lower()) is not None:
                            await webhooks[keyword].send(msg)
Esempio n. 14
0
 async def left_unit(self, msg:discord.Message):
     #select
     c = self.conn.execute(
         sql_format.select_from_unit_by_channel.format(msg.channel.id)
     )
     for row in c:
         #delete
         self.conn.execute(
             sql_format.delete_unit_by_channel.format(msg.channel.id)
         )
         break
     else:
         #not exist DB
         return None
     unit = row[1]
     left = self.client.get_channel(row[0]).guild
     url = row[2]
     #get unit servers
     c = self.conn.execute(sql_format.select_channel_by_unit.format(unit))
     get_server = lambda x: self.client.get_channel(x).guild.name
     servers = [get_server(r[0]) for r in c]
     content = self.create_left_content(left, unit, servers)
     #get and delete webhook
     async with aiohttp.ClientSession() as session:
         try:
             webhook = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session))
             await webhook.send(**content)
             await webhook.delete()
         except Exception as e:
             print(e)
     #send unit server
     c = self.conn.execute(sql_format.select_channel_by_unit.format(unit))
     for row in c:
         await self.send(row[2], **content)
     #send master server
     await self.send(self.master_webhook_by_unit(unit), **content)     
Esempio n. 15
0
    async def on_guild_join(self, guild: discord.Guild):

        await self.bot.db.execute(
            f"INSERT INTO guild_config(id) VALUES ($1) ON CONFLICT DO NOTHING",
            guild.id)

        p = await self.bot.db.fetchrow(
            "SELECT id, prefix FROM guild_config WHERE id = $1", guild.id)

        self.bot.prefixes[guild.id] = p['prefix']

        record = await self.bot.db.fetchrow(
            "SELECT * FROM guild_config WHERE id = $1", guild.id)

        d = self.bot.refresh_template(record)

        self.bot.cache.update(d)

        # Guild information sent to this channel
        embed = discord.Embed(
            title="Guild Joined!",
            description=
            ("```yaml\n"
             f"Guild Name - {guild}\n"
             f"Guild ID - {guild.id}\n"
             f"Guild Owner - {guild.owner} [{guild.owner.id}]\n"
             f"Guild Created - {guild.created_at.strftime('%b %d, %Y %I:%M %p')}\n"
             f"Guild Members - {len(guild.members)}\n"
             "```"),
            timestamp=datetime.datetime.utcnow())
        webhook = Webhook.from_url(self.bot.config['webhook-url'],
                                   adapter=AsyncWebhookAdapter(
                                       self.bot.session))
        await webhook.send(embed=embed,
                           avatar_url=str(guild.icon_url),
                           username=str(guild))
Esempio n. 16
0
    async def on_guild_leave(self, guild):

        with suppress(Exception):
            await self.bot.db.execute("DELETE FROM guild_config WHERE id = $1",
                                      guild.id)

        # Guild information sent to this channel
        embed = discord.Embed(
            title="Guild Left!",
            description=
            ("```yaml\n"
             f"Guild Name - {guild}\n"
             f"Guild ID - {guild.id}\n"
             f"Guild Owner - {guild.owner} [{guild.owner.id}]\n"
             f"Guild Created - {guild.created_at.strftime('%b %d, %Y %I:%M %p')}\n"
             f"Guild Members - {len(guild.members)}\n"
             "```"),
            timestamp=datetime.datetime.utcnow())
        webhook = Webhook.from_url(self.bot.config['webhook-url'],
                                   adapter=AsyncWebhookAdapter(
                                       self.bot.session))
        await webhook.send(embed=embed,
                           avatar_url=str(guild.icon_url),
                           username=str(guild))
Esempio n. 17
0
import requests
import pickle
import discord
import datetime
import time
import re
from discord import Webhook, RequestsWebhookAdapter
from siteItem import SiteItem
from os import path

jordanHook = 'https://discordapp.com/api/webhooks/739924749127516291/Q3rX5AenW1d9E7vB9BA8HBncLmk8u0Y2z3zHR9mMjKqpUZTI_sDqyRl4xM_HN9gatMJk'
yeezyHook = 'https://discordapp.com/api/webhooks/739927902786945105/TnD1CAjmWdJHj5AEiIsbq1SmEr1kD92z6l37qCdBKTuI67_YErcgFSM8buui2cSoMNo1'
nikesbHook = 'https://discordapp.com/api/webhooks/739927996391227493/oZdCOwhdb7uErLSiujwz452Cyja6Fg1lw_1li_25D190BmKrTuSsO0wdmW0uiG90Grip'
offwhiteHook = 'https://discordapp.com/api/webhooks/759493918856314901/prYkYK5AHWYPkFSHH748bYlysot0cfzdNSr3t_xzIg0lGpMnAYWJho731t9FByPVWA2C'

jordan = Webhook.from_url(jordanHook, adapter=RequestsWebhookAdapter())
yeezy = Webhook.from_url(yeezyHook, adapter=RequestsWebhookAdapter())
nikesb = Webhook.from_url(nikesbHook, adapter=RequestsWebhookAdapter())
offwhite = Webhook.from_url(offwhiteHook, adapter=RequestsWebhookAdapter())


def FileCheck(filename):
    global ItemList
    if path.exists(filename):
        filehandler = open(filename, 'rb')
        ItemList = pickle.load(filehandler)
    else:
        ItemList = []


def FileWrite(filename):
Esempio n. 18
0
 def sendDiscordMessage(self, message='Hello world'):
     from discord import Webhook, RequestsWebhookAdapter
     webhook = Webhook.from_url(
         "https://discord.com/api/webhooks/811294684386426890/3SY7GtmBAwyjDM6qr73eDRqrzjRJZ2u0vlShoyOvvf_cCUNvv6YJqiGPI1udVWWqipVp",
         adapter=RequestsWebhookAdapter())
     webhook.send(message)
Esempio n. 19
0
async def guild_notifications_setting_submit(id: int, setting_id: int):
    user = current_app.user_handler.get_user()
    if id in user.guilds_mapping.keys():
        guild = user.guilds_mapping[id]

        if not guild.user_has_access():
            return "No Permissions"

        # Fetch the form info.
        await request.get_data()
        form = await request.form

        # Get the setting.
        setting = current_app.db_session.query(BNSetting).filter_by(
            guild_id=id, channel_id=setting_id).first()
        if setting is None:
            await flash(
                u"Stream Notifications > That is not a valid notifications channel.",
                "danger")
            return redirect(url_for("dashboard.guild_notifications", id=id))

        # Add a subreddit filter.
        if "add_subreddit" in form:
            subreddit = form.get("subreddit_filter", None)
            if subreddit not in current_app.core.rpan_subreddits.list:
                await flash(
                    u"Subreddit Filters > That is an invalid subreddit.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if setting.subreddit_filters:
                if subreddit in setting.subreddit_filters:
                    await flash(
                        u"Subreddit Filters > That subreddit is already added.",
                        "danger")
                    return redirect(
                        url_for("dashboard.guild_notifications", id=id) +
                        f"?setting={setting_id}")

            subreddit_filters = []
            if setting.subreddit_filters is not None:
                subreddit_filters = list(setting.subreddit_filters)
            subreddit_filters.append(subreddit)
            setting.subreddit_filters = subreddit_filters
            current_app.db_session.commit()

            await flash(u"Stream Notifications > Added a subreddit filter.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Add a keyword filter.
        if "add_keyword" in form:
            keyword = form.get("keyword", None)
            if not keyword:
                await flash(u"Keyword Filters > That is an invalid keyword.",
                            "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if setting.keyword_filters:
                if keyword in setting.keyword_filters:
                    await flash(
                        u"Keyword Filters > That keyword is already added.",
                        "danger")
                    return redirect(
                        url_for("dashboard.guild_notifications", id=id) +
                        f"?setting={setting_id}")

                if len(setting.keyword_filters) >= 25:
                    await flash(
                        u"Keyword Filters > This channel has hit the keyword filter limit of 25.",
                        "danger")
                    return redirect(
                        url_for("dashboard.guild_notifications", id=id) +
                        f"?setting={setting_id}")

            keyword_filters = []
            if setting.keyword_filters is not None:
                keyword_filters = list(setting.keyword_filters)
            keyword_filters.append(keyword)
            setting.keyword_filters = keyword_filters
            current_app.db_session.commit()

            await flash(u"Stream Notifications > Added a keyword filter.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Add a user.
        if "add_user" in form:
            username = form.get("username", None)
            if not username:
                await flash(u"Usernames > That is an invalid username.",
                            "warning")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")
            else:
                username = parse_reddit_username(username)

            if not is_valid_reddit_username(username):
                await flash(u"Usernames > That is an invalid Reddit username.",
                            "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if user.id not in current_app.core.settings.ids.bot_developers:
                if username in ["rpanbot"]:
                    await flash(
                        u"Usernames > That is a disallowed username for stream notifications.",
                        "danger")
                    return redirect(
                        url_for("dashboard.guild_notifications", id=id) +
                        f"?setting={setting_id}")

            if setting.users.count() >= 50:
                await flash(
                    u"Usernames > This channel is currently at the limit of 50 users.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            user = current_app.db_session.query(BNUser).filter_by(
                username=username).first()
            if user is None:
                user = BNUser(username=username)
                current_app.db_session.add(user)
            else:
                if setting in user.notifications_for:
                    await flash(
                        u"Usernames > That user is already added to the settings for this channel.",
                        "danger")
                    return redirect(
                        url_for("dashboard.guild_notifications", id=id) +
                        f"?setting={setting_id}")

            setting.users.append(user)
            current_app.db_session.commit()

            await flash(u"Usernames > Added a user to the notifications.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Remove a subreddit filter.
        if "remove_subreddit" in form:
            subreddit = form.get("remove_subreddit", None)
            if not subreddit:
                await flash(
                    u"Subreddit Filters > That is an invalid subreddit.",
                    "warning")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if not setting.subreddit_filters or subreddit not in setting.subreddit_filters:
                await flash(
                    u"Subreddit Filters > That is not an added subreddit filter.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            subreddit_filters = list(setting.subreddit_filters)
            subreddit_filters.remove(subreddit)
            setting.subreddit_filters = subreddit_filters
            current_app.db_session.commit()

            await flash(u"Subreddit Filters > Removed a subreddit filter.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Remove a keyword filter.
        if "remove_keyword" in form:
            keyword_index = form.get("remove_keyword", None)
            if not keyword_index:
                await flash(u"Keyword Filters > That is an invalid keyword.",
                            "warning")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")
            else:
                keyword_index = int(keyword_index)

            if not setting.keyword_filters:
                await flash(
                    u"Keyword Filters > There are no keyword filters on this guild.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if keyword_index not in range(0, len(setting.keyword_filters) - 1):
                await flash(
                    u"Keyword Filters > That is not an added keyword filter.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            keyword_filters = list(setting.keyword_filters)
            del keyword_filters[keyword_index]
            setting.keyword_filters = keyword_filters
            current_app.db_session.commit()

            await flash(u"Keyword Filters > Removed a keyword filter.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Remove a user.
        if "remove_user" in form:
            username = form.get("remove_user", None)
            if not username:
                await flash(u"Users > That is an invalid username.", "warning")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if not is_valid_reddit_username(username):
                await flash(u"Users > That is not a valid Reddit username.",
                            "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            user = current_app.db_session.query(BNUser).filter_by(
                username=username).first()

            is_valid_removal = True
            if user is None:
                is_valid_removal = False
            elif setting not in user.notifications_for:
                is_valid_removal = False

            if not is_valid_removal:
                await flash(
                    u"Users > That user is not in the settings for this channel.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            setting.users.remove(user)
            current_app.db_session.commit()

            await flash(
                f"Users > You will no longer receive notifications for u/{username} in this channel.",
                "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Setting custom text
        if "set_custom_text" in form:
            custom_text = form.get("custom_text", None)
            if not custom_text:
                setting.custom_text = ""
                current_app.db_session.commit()

                await flash(
                    u"Custom Text > Succesfully removed your custom text.",
                    "success")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            if len(custom_text) > 1000:
                await flash(
                    u"Custom Text > That custom text is beyond the 1000 character limit.",
                    "danger")
                return redirect(
                    url_for("dashboard.guild_notifications", id=id) +
                    f"?setting={setting_id}")

            setting.custom_text = custom_text
            current_app.db_session.commit()

            await flash(u"Custom Text > Succesfully set the custom text.",
                        "success")
            return redirect(
                url_for("dashboard.guild_notifications", id=id) +
                f"?setting={setting_id}")

        # Deleting the setting.
        if "delete_setting" in form:
            try:
                async with ClientSession() as session:
                    webhook = Webhook.from_url(
                        setting.webhook_url,
                        adapter=AsyncWebhookAdapter(session))
                    await webhook.delete(reason="Deleted via web panel.")
            except Exception as e:
                print(e)
                pass
            finally:
                current_app.db_session.delete(setting)
                current_app.db_session.commit()

            await flash(
                f"Stream Notifications > Deleted the notification setting for {setting.channel_id}.",
                "success")
            return redirect(url_for("dashboard.guild_notifications", id=id))

        return redirect(
            url_for("dashboard.guild_notifications", id=id) +
            f"?setting={setting_id}")
    else:
        return "Guild Not Found", 404
        "author": {
            "name": "Classic Loot Manager has been updated!"
        },
        "title":
        name,
        "color":
        14464841,
        "fields": [{
            "name": "**Version**",
            "value": "`" + tag + "`",
            "inline": False
        }, {
            "name": "**CHANGELOG**",
            "value": "```" + body + "```",
            "inline": False
        }],
        "footer": {
            "text": "Released by " + author
        }
    }

    if prerelease:
        embed[
            "description"] = "_This is a beta version and may still contain bugs_"

    webhook = Webhook.from_url(sys.argv[1], adapter=RequestsWebhookAdapter())
    webhook.send(embed=Embed.from_dict(embed))
except Exception as e:
    print(str(e))
    exit(30)
Esempio n. 21
0
async def post_to_discord(url: str, **kwargs: dict):
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session))
        await webhook.send(**kwargs)
Esempio n. 22
0
async def write_chat(ignname, content, avatar):
    url = urlparse(avatar)
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(webhook_url,
                                   adapter=AsyncWebhookAdapter(session))
        await webhook.send(content, username=ignname, avatar_url=url.geturl())
Esempio n. 23
0
async def error_log(content: str) -> None:
    if not ERROR:
        return
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(ERROR, adapter=AsyncWebhookAdapter(session))
        await webhook.send(content, username="******")
Esempio n. 24
0
async def join_leave_log(embed: discord.Embed) -> None:
    if not GUILD:
        return
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(GUILD, adapter=AsyncWebhookAdapter(session))
        await webhook.send(embed=embed, username="******")
Esempio n. 25
0
 async def foo(self, embed, url, name):
     async with aiohttp.ClientSession() as session:
         webhook = Webhook.from_url(url,
                                    adapter=AsyncWebhookAdapter(session))
         await webhook.send(embed=embed, username=name)
Esempio n. 26
0
teesHook = 'https://discordapp.com/api/webhooks/735546285670793286/L-xeCHvD3cVAJcmKT3tY02VmRn8tdC7yKHUzcbgFGw-fOA4mn3m2tIeZoSYd7LtNTRzk'
crewnecksHook = 'https://discordapp.com/api/webhooks/735546415572320318/tSJyCVZIfUhzUqlUkH_RVn1kQdSwsXvUREJe6rP1grF_c4qSB3MG0chJlz9irat-1aNV'
headwearHook = 'https://discordapp.com/api/webhooks/735546525035397181/7qtY0IQ772olXqrGkvXsjvwPAW3o4k0St68M30MHYjeo-dhOtnZogMjXCEDi1PvmR5zW'
hoodiesHook = 'https://discordapp.com/api/webhooks/735546643075825745/w6p9jK_b5V8tlT43V7Jl-jrJQpu-jXASoDA3COy4JYlL05P1_AypbY6lVIi8gh8lV6qc'
outerwearHook = 'https://discordapp.com/api/webhooks/735546768749756570/ku87ASQtE3zjodReKiWsJrHUu__A2gmsC92ezh1wZMvZys9CuxhK6-zEycm8ACgsD7kq'
pantsHook = 'https://discordapp.com/api/webhooks/735546846545576038/mDH30yvrYH7QUzZgi3lGdEfIBYC6490rnHWYMiv61lzff-BIfaPhOjRZoZUGwNQ0wsvL'
shortsHook = 'https://discordapp.com/api/webhooks/735546928590356534/r4P0-WH7Or-k4giqu7Gqh1vN_Hm23PsYZGHFv-sRYQw3sllcYLa-O1zfDS6ejewNw27a'
sneakersHook = 'https://discordapp.com/api/webhooks/735547061201535009/qkQ3Zlf2aLRafaNI6qUR4SF8_qdE4sOGboKTZx9wJGTWaqhpMFYdGxm0V9xJ-rMYA2Qo'
socksHook = 'https://discordapp.com/api/webhooks/735547216629989408/ACqfDINlt-jeBus89zUa7-SQxhAX-VspzdZNUDHdzoROe_gXsakAFRI9chRQZOu30mCf'
lifestyleHook = 'https://discordapp.com/api/webhooks/735547299027091598/-IEBz93lzehLn-Dz-mUThTeSqG4fotpXnmzaepggnGB7P_S2505XzzyQhDyh-mqDsa8G'
accessoriesHook = 'https://discordapp.com/api/webhooks/735547411354746921/PWR76VpUXTL9UqcubEHV6cZspUijmosZrF8IgwbKniN0F7d2dkxJeajNoMPncoykCwHb'
buttonupsHook = 'https://discordapp.com/api/webhooks/735547485103063084/ScptREN_rv8JFoOLDDtBEi_SicAxjNR3uvJ8Nj_JAn2lfwFpNVv9wqTlqi4RTwOe-HaK'
onesiesHook = 'https://discordapp.com/api/webhooks/735547580338929666/MVttJsiwzzb8kT4-1dhMjp1fhbkOHwqzTvdobQDjVnhCCRnh1MjEdObi3MO0pvtxTbdw'

tees = Webhook.from_url(teesHook, adapter=RequestsWebhookAdapter())
crewnecks = Webhook.from_url(crewnecksHook, adapter=RequestsWebhookAdapter())
headwear = Webhook.from_url(headwearHook, adapter=RequestsWebhookAdapter())
hoodies = Webhook.from_url(hoodiesHook, adapter=RequestsWebhookAdapter())
outerwear = Webhook.from_url(outerwearHook, adapter=RequestsWebhookAdapter())
pants = Webhook.from_url(pantsHook, adapter=RequestsWebhookAdapter())
shorts = Webhook.from_url(shortsHook, adapter=RequestsWebhookAdapter())
sneakers = Webhook.from_url(sneakersHook, adapter=RequestsWebhookAdapter())
socks = Webhook.from_url(socksHook, adapter=RequestsWebhookAdapter())
lifestyle = Webhook.from_url(lifestyleHook, adapter=RequestsWebhookAdapter())
accessories = Webhook.from_url(accessoriesHook,
                               adapter=RequestsWebhookAdapter())
buttonups = Webhook.from_url(buttonupsHook, adapter=RequestsWebhookAdapter())
onesies = Webhook.from_url(onesiesHook, adapter=RequestsWebhookAdapter())

Esempio n. 27
0
import datetime
import time
import re
from discord import Webhook, RequestsWebhookAdapter
from siteItem import SiteItem
from os import path

if path.exists('extrabutter_list.dat'):
    filehandler = open('extrabutter_list.dat', 'rb')
    ItemList = pickle.load(filehandler)
else:
    ItemList = []

extrabutterHook = 'https://discordapp.com/api/webhooks/738473993438363789/QFRvfT1BbVsFcrcLhmfn_YYTbjparZ3TWqx4N0zkX9upwEYZmhiO3pStOaiQKqa0mjDJ'

extrabutter = Webhook.from_url(extrabutterHook,
                               adapter=RequestsWebhookAdapter())

jordanHook = 'https://discordapp.com/api/webhooks/739924749127516291/Q3rX5AenW1d9E7vB9BA8HBncLmk8u0Y2z3zHR9mMjKqpUZTI_sDqyRl4xM_HN9gatMJk'
yeezyHook = 'https://discordapp.com/api/webhooks/739927902786945105/TnD1CAjmWdJHj5AEiIsbq1SmEr1kD92z6l37qCdBKTuI67_YErcgFSM8buui2cSoMNo1'
nikesbHook = 'https://discordapp.com/api/webhooks/739927996391227493/oZdCOwhdb7uErLSiujwz452Cyja6Fg1lw_1li_25D190BmKrTuSsO0wdmW0uiG90Grip'

jordan = Webhook.from_url(jordanHook, adapter=RequestsWebhookAdapter())
yeezy = Webhook.from_url(yeezyHook, adapter=RequestsWebhookAdapter())
nikesb = Webhook.from_url(nikesbHook, adapter=RequestsWebhookAdapter())


def ExistsInList(item):
    ind = -1
    for Item in ItemList:
        ind += 1
        if Item.Name == item.Name and Item.Color == item.Color:
Esempio n. 28
0
import requests
from bs4 import BeautifulSoup
import re
from discord import Webhook, RequestsWebhookAdapter

from datetime import datetime


webhook = Webhook.from_url("", adapter=RequestsWebhookAdapter())

# Fill in your details here to be posted to the login form.
payload = {
    'login_username': '******',••••••••
    'login_password': ''
}
def GodWatch():
	Gods = []
	CurrentSpawn = []
	with requests.Session() as s:
		webhook.send("Starting a new session")
		p = s.post('https://sigil.outwar.com/login', data=payload)
		while True:
			now = datetime.now()
			current_time = now.strftime("%H:%M:%S")
			print(current_time)
			
			me = s.get('https://sigil.outwar.com/world?suid=******&serverid=1')
			vault = s.get('https://sigil.outwar.com/raidtools')
			soup = BeautifulSoup(vault.content, 'html.parser')
			for a in soup.find_all("a", text=re.compile('Teleport to ')):
				God = a.text.replace("Teleport to ", "")
Esempio n. 29
0
async def inv():
    global inva
    global invb
    invasions = requests.get('https://api.warframestat.us/pc/invasions').json()
    for invasion in invasions:
        if invasion['id'] not in inva:
            node = invasion['node']
            if invasion['vsInfestation'] == True:
                attackReward = 'None'
                defendReward = invasion['defenderReward']['countedItems'][0]
                for i in invasionitem:
                    if i in defendReward['type'] or i in defendReward['type']:
                        embed = discord.Embed(title=invasion['node'],
                                              colour=discord.Colour(invasion['attackerReward']['color']))
                        embed.add_field(name=invasion['attackingFaction'], value=attackReward, inline=False)
                        embed.add_field(name=invasion['defendingFaction'], value=defendReward['type'], inline=False)
                        embed.set_author(name=invasion['desc'])
                        embed.set_thumbnail(url=invasion['defenderReward']['thumbnail'])
                        embed.set_footer(text=invasion['id'])
                        for i in servers:
                            try:
                                guild = bot.get_guild(i['serverid'])
                            except:
                                pass
                            content = ''
                            try:
                                role = discord.utils.get(guild.roles, name='Potato')
                                content+=' '+role.mention
                            except:
                                pass
                            try:
                                async with aiohttp.ClientSession() as session:
                                    webhook = Webhook.from_url(i['giftinvasionswebhook'], adapter=AsyncWebhookAdapter(session))
                                    await webhook.send(content=content, embed=embed)
                            except:
                                pass
            else:
                defendReward = invasion['defenderReward']['countedItems'][0]
                attackReward = invasion['attackerReward']['countedItems'][0]
                for i in invasionitem:
                    if i in defendReward['type'] or i in defendReward['type']:
                        embed = discord.Embed(title=invasion['node'],
                                              colour=discord.Colour(1))
                        embed.add_field(name=invasion['attackingFaction'], value=attackReward['type'], inline=False)
                        embed.add_field(name=invasion['defendingFaction'], value=defendReward['type'], inline=False)
                        embed.set_author(name=invasion['desc'])
                        if i in defendReward['type']:
                            embed.set_thumbnail(url=invasion['defenderReward']['thumbnail'])
                        else:
                            embed.set_thumbnail(url=invasion['attackerReward']['thumbnail'])
                        embed.set_footer(text=invasion['id'])
                        for i in servers:
                            try:
                                guild = bot.get_guild(i['serverid'])
                            except:
                                pass
                            content = ''
                            try:
                                role = discord.utils.get(guild.roles, name='Potato')
                                content+=' '+role.mention
                            except:
                                pass
                            try:
                                async with aiohttp.ClientSession() as session:
                                    webhook = Webhook.from_url(i['giftinvasionswebhook'], adapter=AsyncWebhookAdapter(session))
                                    await webhook.send(content=content, embed=embed)
                            except:
                                pass
            inva.append(invasion['id'])
        invb.append(invasion['id'])
    for i in inva:
        if i not in invb:
            inva.remove(i)
Esempio n. 30
0
    async def on_command_error(ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            ctx.command.reset_cooldown(ctx)
            await ctx.send_cmd_help(ctx)
        elif isinstance(error, commands.BadArgument):
            ctx.command.reset_cooldown(ctx)
            await ctx.send_cmd_help(ctx)
        elif isinstance(error, commands.DisabledCommand):
            pass
        elif isinstance(error, commands.CommandOnCooldown):
            fmt = (str(error)).split()
            word = fmt[7].strip("s")
            time = float(word)
            timer = round(time, 0)
            delta = str(timedelta(seconds=int(timer))).lstrip("0").lstrip(":")
            await ctx.send(f"❌ lol, rate limits You can try again in `{delta}`"
                           )
        elif isinstance(error, commands.CommandNotFound):
            pass
        elif isinstance(error, commands.CheckFailure):
            ctx.command.reset_cooldown(ctx)
            pass
        elif isinstance(error, commands.BotMissingPermissions):
            ctx.command.reset_cooldown(ctx)
            await ctx.send(error.missing_perms)
        elif isinstance(error, commands.CheckFailure):
            ctx.command.reset_cooldown(ctx)
            pass
        elif isinstance(error, commands.NoPrivateMessage):
            ctx.command.reset_cooldown(ctx)
            await ctx.send("Nope that command is not available in DMs.")

        else:
            if ctx.bot.debug:
                ctx.bot.log.error(f"shit: {repr(error)}", exc_info=True)
            else:
                ctx.bot.log.error(f"shit: {repr(error)}", exc_info=False)
            ctx.command.reset_cooldown(ctx)
            webhook = Webhook.from_url(ctx.bot.keys['error_wh'],
                                       adapter=AsyncWebhookAdapter(
                                           ctx.bot.session))
            await webhook.edit(name="Error")
            channel = ctx.message.channel
            t = datetime.datetime.now()
            avatar = ctx.bot.user.avatar_url
            fmt = '[ %I:%M:%S ] %B/%d/%Y'
            long = "".join(
                traceback.format_exception(type(error), error,
                                           error.__traceback__))
            error_title = "Error"
            desc = '`{}: {}`'.format(
                type(error.original).__name__, str(error.original))
            em = discord.Embed(color=0xFF0000, description=desc)
            em.set_author(name=error_title, icon_url=avatar)
            em.set_footer(text=t.strftime(fmt))
            em.add_field(name="Content", value=ctx.message.content)
            em.add_field(name="Invoker",
                         value="{}\n({})".format(ctx.message.author.mention,
                                                 str(ctx.message.author)))
            c = "Private channel" if isinstance(ctx.message.channel, discord.abc.PrivateChannel) else \
                f"{channel.mention}\n({channel.name})"
            em.add_field(name="Channel", value=c)
            if not isinstance(ctx.message.channel, discord.abc.PrivateChannel):
                em.add_field(name="Guild", value=ctx.message.guild.name)
            await webhook.send(embed=em)
            print(long)
            pages = pagify(str(long))
            if pages:
                for page in pages:
                    await webhook.send(f"```py\n{page}\n```")
            er = f"Error in command '**__{ctx.command.qualified_name}__**' - `{type(error.original).__name__}`: `" \
                 f"{str(error.original)}` "
            e = discord.Embed(title="**Error** :x:",
                              description="Error in command",
                              color=0xFFC0CB)
            e.add_field(name="traceback", value=er)
            await channel.send(embed=e)
Esempio n. 31
0
def log(message: str):
    print(message)
    log_url = config('LOGGER_URL')
    webhook = Webhook.from_url(log_url, adapter=RequestsWebhookAdapter())
    webhook.send(message)