Esempio n. 1
0
def send_webhook_message(application, action):
    message_to_send = format_message(application, action)
    webhook = DiscordWebhook(url=DISCORD_WEBHOOK_URL, content=message_to_send)

    if ATTACH_LOGS:
        application_logs = lookup_application_logs(application)
        syslogs = lookup_application_logs('Server')

        if application_logs is not False:
            with open(application_logs, "rb+") as f:
                filename = application + '.txt'
                webhook.add_file(file=f.read(), filename=filename)

        if syslogs is not False:
            with open(syslogs, "rb+") as f:
                filename = syslogs + '.txt'
                webhook.add_file(file=f.read(), filename=filename)

    if EMBED_LOGS:
        application_logs = lookup_application_logs(application)
        syslogs = lookup_application_logs('Server')

        if application_logs is not False:
            embed = DiscordEmbed(title=application,
                                 description=tail(application_logs, 10))
            webhook.add_embed(embed)

        if syslogs is not False:
            embed = DiscordEmbed(title='/var/log/syslog',
                                 description=tail(syslogs, 10))
            webhook.add_embed(embed)

    webhook.execute()
Esempio n. 2
0
def send_alert(data):
    if config.send_telegram_alerts:
        tg_bot = Bot(token=config.tg_token)
        try:
            tg_bot.sendMessage(data['telegram'],
                               data['msg'].encode('latin-1', 'backslashreplace').decode('unicode_escape'),
                               parse_mode='MARKDOWN')
        except KeyError:
            tg_bot.sendMessage(config.channel,
                               data['msg'].encode('latin-1', 'backslashreplace').decode('unicode_escape'),
                               parse_mode='MARKDOWN')
        except Exception as e:
            print('[X] Telegram Error:\n>', e)

    if config.send_discord_alerts:
        try:
            webhook = DiscordWebhook(url="https://discord.com/api/webhooks/" + data['discord'])
            embed = DiscordEmbed(title=data['msg'])
            webhook.add_embed(embed)
            response = webhook.execute()
        except KeyError:
            webhook = DiscordWebhook(url="https://discord.com/api/webhooks/" + config.discord_webhook)
            embed = DiscordEmbed(title=data['msg'])
            webhook.add_embed(embed)
            response = webhook.execute()
        except Exception as e:
            print('[X] Discord Error:\n>', e)

    if config.send_slack_alerts:
        try:
            slack = Slack(url='https://hooks.slack.com/services/' + data['slack'])
            slack.post(text=data['msg'])
        except KeyError:
            slack = Slack(url='https://hooks.slack.com/services/' + config.slack_webhook)
            slack.post(text=data['msg'])
        except Exception as e:
            print('[X] Slack Error:\n>', e)

    if config.send_twitter_alerts:
        tw_auth = tweepy.OAuthHandler(config.tw_ckey, config.tw_csecret)
        tw_auth.set_access_token(config.tw_atoken, config.tw_asecret)
        tw_api = tweepy.API(tw_auth)
        try:
            tw_api.update_status(status=data['msg'].replace('*', '').replace('_', '').replace('`', ''))
        except Exception as e:
            print('[X] Twitter Error:\n>', e)

    if config.send_email_alerts:
        try:
            email_msg = MIMEText(data['msg'].replace('*', '').replace('_', '').replace('`', ''))
            email_msg['Subject'] = config.email_subject
            email_msg['From'] = config.email_sender
            email_msg['To'] = config.email_sender
            context = ssl.create_default_context()
            with smtplib.SMTP_SSL(config.email_host, config.email_port, context=context) as server:
                server.login(config.email_user, config.email_password)
                server.sendmail(config.email_sender, config.email_receivers, email_msg.as_string())
                server.quit()
        except Exception as e:
            print('[X] Email Error:\n>', e)
def send_war_nag(config, current_war, member_list):

    nagConfig = WarNagConfig(config, current_war, member_list)

    if nagConfig.abort or nagConfig.naughty_member_list == '':
        return

    logger.debug('Sending nag webhook')
    webhook = DiscordWebhook(url=nagConfig.webhook_url)

    # add list of naughty users as embed embed object to webhook
    embed = DiscordEmbed(title=nagConfig.nag_header,
                         description=nagConfig.naughty_member_list,
                         color=int('0xff5500', 16))

    if nagConfig.quit_member_list:
        webhook.add_embed(embed)
        embed = DiscordEmbed(
            title=config['strings']['discord-header-war-quit'].format(),
            description=nagConfig.quit_member_list,
            color=int('0x660000', 16))

    embed.set_footer(text='crtools v{}'.format(__version__))
    embed.set_timestamp()

    webhook.add_embed(embed)

    webhook.execute()
Esempio n. 4
0
def post_to_discord(prev_minutes, current_hours, tc_fname, tc_lname, tc_cid,
                    tc_hours):
    # create embed object for webhook
    embed = DiscordEmbed(
        title='Weekly Statistics',
        description='Statustics for the week of {}.{}.{}'.format(
            today.year, today.month, today.day),
        color=242424)

    # set image
    embed.set_thumbnail(
        url='https://image.prntscr.com/image/mTFpZeXOR8_lGUTO8gVg-Q.png')

    current_hours = round(current_hours / 60 / 60, 1)

    embed.add_embed_field(name='This Weeks Hours',
                          value='{}'.format(current_hours))
    embed.add_embed_field(name='Last Weeks Hours',
                          value='{}'.format(prev_minutes))
    embed2 = DiscordEmbed(
        title='This weeks top controller:',
        description='{0} {1} - CID: {2} with {3} hours! Congratulations!'.
        format(tc_fname, tc_lname, tc_cid, tc_hours),
        color=242424)

    # Post fun stuff to Discord
    webhook = DiscordWebhook(url=discord_webhook)

    # add embed object to webhook
    webhook.add_embed(embed)
    webhook.add_embed(embed2)
    webhook.execute()
Esempio n. 5
0
def send_war_nag(config, current_war, member_list):

    nag_config = WarNagConfig(config, current_war, member_list)

    if nag_config.abort or (nag_config.naughty_member_list == ''):
        return True

    webhook = DiscordWebhook(url=nag_config.webhook_url)

    # add list of naughty users as embed embed object to webhook
    embed = DiscordEmbed(title=nag_config.nag_header,
                         description=nag_config.naughty_member_list,
                         color=int('0xff5500', 16))

    if nag_config.quit_member_list:
        webhook.add_embed(embed)
        embed = DiscordEmbed(
            title=config['strings']['discord-header-war-quit'].format(),
            description=nag_config.quit_member_list,
            color=int('0x660000', 16))

    embed.set_footer(text='crtools v{}'.format(__version__))
    embed.set_timestamp()

    webhook.add_embed(embed)

    try:
        logger.info('Sending war nag to Discord')
        webhook.execute()
    except ConnectionError as e:
        logger.error(
            'Connection to discord failed. Sending war nag webhook failed.')
        return False

    return True
Esempio n. 6
0
    def handle(self, *args, **options):

        # marketers = User.objects.filter(Q(role__name='marketer') | Q(role__name='admin'))

        teams = Team.objects.all()
        for team in teams:
            today_date = timezone.now().date() - timedelta(days=1)
            marketers = team.employees.filter(role__name='marketer')
            total_submissions_company = 0
            employee = ''
            for marketer in marketers:
                total_submission = Submission.objects.filter(
                    lead__marketer=marketer).filter(
                        created=today_date).count()
                employee += '{0} : {1}'.format(marketer.full_name,
                                               total_submission) + '\n'
                total_submissions_company += total_submission

            webhook = DiscordWebhook(
                url=discord_url,
                username=team.name,
                content="**Submission Made on {0}**".format(today_date))
            text = 'Total Submissions = {0}'.format(total_submissions_company)
            if total_submissions_company > 0:
                embed = DiscordEmbed(description=text, color=242424)
                list = DiscordEmbed(description=employee, color=242424)
                webhook.add_embed(embed)
                webhook.add_embed(list)
            else:
                text = 'No submission for {0}'.format(today_date)
                embed = DiscordEmbed(description=text)
                webhook.add_embed(embed)

            webhook.execute()
Esempio n. 7
0
def quest_mon_var(monid, mon, shiny, typeid, formid):
    mariadb_connection = mariadb.connect(user=user,
                                         password=passwd,
                                         database=database,
                                         host=host)
    cursor = mariadb_connection.cursor()
    query = (
        "select CONVERT(pokestop.name USING UTF8MB4) as pokestopname,pokestop.latitude,pokestop.longitude,quest_task from pokestop inner join trs_quest on pokestop.pokestop_id = trs_quest.GUID where quest_pokemon_id ="
        + monid + " and quest_pokemon_form_id =" + typeid +
        " and ST_CONTAINS(ST_GEOMFROMTEXT('POLYGON((" + area +
        "))'), point(pokestop.latitude, pokestop.longitude))")
    cursor.execute(query)
    name = cursor.fetchall()

    if not name:
        print("no quests for " + mon)
    else:
        #convert data into string
        res = [tuple(str(ele) for ele in sub) for sub in name]
        webhook = DiscordWebhook(url=webhookurl)
        # create embed object for webhook
        research = ''
        for stop in res:
            research += ('[' + stop[0] + ']('
                         'https://www.google.com/maps/search/?api=1&query='
                         '' + stop[1] + ',' + stop[2] + ')' + ' ' + stop[3] +
                         '\n')
            if len(research) > 1900:
                print("larger then 2048 breaking up")
                print(mon + " Length:", len(research))
                embed = DiscordEmbed(title=shiny + mon + ' Field Research' +
                                     shiny,
                                     description=research,
                                     color=16777011)
                embed.set_thumbnail(
                    url=
                    'https://raw.githubusercontent.com/whitewillem/PogoAssets/resized/no_border/pokemon_icon_'
                    + monid + '_' + formid + '.png')
                embed.set_footer(text='Research by ' + author)
                #add embed object to webhook
                webhook.add_embed(embed)
                webhook.execute()
                research = ''
                webhook.remove_embed(0)
                time.sleep(2)

        print(mon + " Length:", len(research))
        embed = DiscordEmbed(title=shiny + mon + ' Field Research' + shiny,
                             description=research,
                             color=16777011)
        embed.set_thumbnail(
            url=
            'https://raw.githubusercontent.com/whitewillem/PogoAssets/resized/no_border/pokemon_icon_'
            + monid + '_' + formid + '.png')
        embed.set_footer(text='Research by ' + author)
        #add embed object to webhook
        webhook.add_embed(embed)
        webhook.execute()
        research = ''
        time.sleep(2)
def discord_webhook(callsign, name, cid, rating_long, server, status):

    webhook = DiscordWebhook(url=webhookurl)

    if status == "online":
        embed = DiscordEmbed(title=callsign + " - Online", description=callsign + ' is now online on the VATSIM network.', color=65290)
        embed.set_footer(text='ZDC VATSIM Notify Bot ' + version, icon_url='https://vzdc.org/photos/discordbot.png')
        embed.set_thumbnail(url='https://vzdc.org/photos/logo.png')
        embed.set_timestamp()
        embed.add_embed_field(name='Name', value=name)
        embed.add_embed_field(name='Rating', value=rating_long)
        embed.add_embed_field(name='CID', value=cid)
        embed.add_embed_field(name='Callsign', value=callsign)
        embed.add_embed_field(name='Server', value=server)

        webhook.add_embed(embed)
        webhook.execute()
        webhook.remove_embed(0)
        
    else:
        embed = DiscordEmbed(title=callsign + " - Offline", description=callsign + ' is now offline on the VATSIM network.', color=16711683)
        embed.set_footer(text='ZDC VATSIM Notify Bot ' + version, icon_url='https://vzdc.org/photos/discordbot.png')
        embed.set_thumbnail(url='https://vzdc.org/photos/logo.png')
        embed.set_timestamp()
        #embed.add_embed_field(name='Name', value=name)
        #embed.add_embed_field(name='Rating', value=rating_long)
        #embed.add_embed_field(name='CID', value=cid)
        #embed.add_embed_field(name='Callsign', value=callsign)
        #embed.add_embed_field(name='Server', value=server)

        webhook.add_embed(embed)
        webhook.execute()
        webhook.remove_embed(0)
Esempio n. 9
0
def rocket(leader, lname, sprite, guide):
    mariadb_connection = mariadb.connect(user=user,
                                         password=passwd,
                                         database=database,
                                         host=host,
                                         port=port)
    cursor = mariadb_connection.cursor()
    query = (
        "select CONVERT(pokestop.name USING UTF8MB4) as pokestopname,pokestop.latitude,pokestop.longitude from pokestop WHERE incident_grunt_type = "
        + leader + " and ST_CONTAINS(ST_GEOMFROMTEXT('POLYGON((" + area +
        "))'), point(pokestop.latitude, pokestop.longitude))")
    cursor.execute(query)
    name = cursor.fetchall()

    if not name:
        print("Leader not Found: " + lname)
    else:
        #convert data into string
        res = [tuple(str(ele) for ele in sub) for sub in name]
        res.sort()
        webhook = DiscordWebhook(url=webhookurlr)
        # create embed object for webhook
        research = ''
        for stop in res:
            research += ('[' + stop[0] + ']('
                         'https://maps.google.com/?q='
                         '' + stop[1] + ',' + stop[2] + ')' + '\n')
            if len(research) > 1900:
                print("larger then 2048 breaking up")
                print(lname + " Length:", len(research))
                embed = DiscordEmbed(title='Leader: ' + lname,
                                     description=research,
                                     color=3158064,
                                     url=guide)
                embed.set_thumbnail(url=sprite)
                embed.set_footer(text='Leader Locations by: ' + author)
                embed.set_author(name=lname + ' Counters Guide Link',
                                 url=guide)
                #add embed object to webhook
                webhook.add_embed(embed)
                webhook.execute()
                research = ''
                webhook.remove_embed(0)
                time.sleep(2)

        print(lname + " Length:", len(research))
        embed = DiscordEmbed(title='Leader: ' + lname,
                             description=research,
                             color=3158064,
                             url=guide)
        embed.set_thumbnail(url=sprite)
        embed.set_footer(text='Leader Locations by: ' + author,
                         icon_url=footerimg)
        embed.set_author(name=lname + ' Counters Guide Link', url=guide)
        #add embed object to webhook
        webhook.add_embed(embed)
        webhook.execute()
        research = ''
        time.sleep(2)
Esempio n. 10
0
def main():
    # When changing links, make sure to delete the database.json file
    hook = "https://discordapp.com/api/webhooks/698641374895145021/DpTKruC5Q_XgqBCBxTwBKMLJVSrQnxsFYbmDJONtagmV-NyYs0dK4SpHm_akIwLbqXb5"
    link = "https://moanabikini.com"
    try:
        with open("database.json", "r") as database:
            dbjson = loads(database.read())
            id_list = list(map(lambda prod: prod["id"], dbjson))
    except FileNotFoundError:
        print("Making Request")
        json = get_json(link)
        with open("database.json", "w") as database:
            dump(json, database)
        id_list = list(map(lambda prod: prod["id"], json))

    while True:
        print("Scraping")
        json = get_json(link)
        with open("database.json", "r") as database:
            dbjson = loads(database.read())

        for product in json:
            if product["id"] not in id_list:
                with open("database.json", "w") as database:
                    dump(json, database)
                print("New Item Found")
                webhook = DiscordWebhook(url=hook)
                embed = DiscordEmbed(title=product["title"])
                embed.set_image(url=product["images"][0]["src"])
                for variant in product["variants"]:
                    embed.add_embed_field(name=f'{variant["title"]} -- {variant["price"]}',
                                          value=f"[Purchase]({link}/cart/{variant['id']}:1) -- AVAILABLE: {variant['available']}",
                                          inline=True)
                webhook.add_embed(embed)
                webhook.execute()
                id_list.append(product["id"])
            else:
                for product2 in dbjson:
                    if product["id"] == product2["id"]:
                        for variant in product["variants"]:
                            for variant2 in product2["variants"]:
                                if (variant["id"] == variant2["id"]) and (not variant2["available"] and variant["available"]):
                                    webhook = DiscordWebhook(url=hook)
                                    embed = DiscordEmbed(
                                        title=f'{product["title"]} RESTOCK in size {variant["title"]}')
                                    embed.set_image(
                                        url=product["images"][0]["src"])
                                    for variant in product["variants"]:
                                        embed.add_embed_field(
                                            name=f'{variant["title"]} -- {variant["price"]}', value=f"[Purchase]({link}/cart/{variant['id']}:1) -- AVAILABLE: {variant['available']}", inline=True)
                                    webhook.add_embed(embed)
                                    webhook.execute()
                                    with open("database.json", "w") as database:
                                        dump(json, database)

        time.sleep(5)
    print(id_list)
Esempio n. 11
0
def routiney():
    fl('r.txt')
    fl('hook.txt')
    f=open('hook.txt','r')
    f=f.read()
    hooks=f.split()
    total=len(f)
    if total==0:
        return
    for post in get_posts('officialroutineofnepalbanda', pages=1):
        time=str(post['post_id'])
        f = open("r.txt", "r")
        prev=f.read()
        old=re.search(time, prev)
        if old==None: 
            if(str(post['video'])!='None'):
              webhook = DiscordWebhook(username='******', avatar_url='https://pbs.twimg.com/profile_images/777188003445739521/t5GNGfAc_400x400.jpg', url=hooks, content=str(post['text'])+'\n<'+str(post['post_url'])+'>\n'+str(post['video']))
              webhook.execute()
              continue
            webhook = DiscordWebhook(username='******', avatar_url='https://pbs.twimg.com/profile_images/777188003445739521/t5GNGfAc_400x400.jpg', url=hooks)
            embed = DiscordEmbed(description=str(post['text']))            
            embed.set_author(name='Routiney', url=post['post_url'], icon_url='https://pbs.twimg.com/profile_images/777188003445739521/t5GNGfAc_400x400.jpg')
            img = post['images']
            try:
                imgcount=len(img)
                if(imgcount>2):
                    webhook.add_embed(embed)
                    webhook.execute()
                    for imgs in post['images']:
                        webhook = DiscordWebhook(username='******', avatar_url='https://cdn.discordapp.com/app-icons/786534057437691914/8dd876fd77d51452a5e3b3df4bc0ce18.png?size=256', url=hooks)
                        embed = DiscordEmbed(description='\u200b')
                        embed.set_image(url=imgs)
                        webhook.add_embed(embed)
                        webhook.execute()
                else:
                    try:
                        embed.set_image(url=img[1])
                        embed.set_thumbnail(url=img[0])
                    except:
                        embed.set_image(url=post['image'])
                    embed.set_footer(text='Blah Blah Blah ...') 
                    webhook.add_embed(embed)
                    response = webhook.execute()
             except:
                    embed.set_image(url=post['image'])
                    webhook.add_embed(embed)
                    webhook.execute()                    
            last=str(post['time'])
            f = open("r.txt", "a")
            f.write(last)
            f.close()
    ok()
Esempio n. 12
0
def quest_stardust(itemid, item, sprite):
    mariadb_connection = mariadb.connect(user=user,
                                         password=passwd,
                                         database=database,
                                         host=host)
    cursor = mariadb_connection.cursor()
    query = (
        "select CONVERT(pokestop.name USING UTF8MB4) as pokestopname,pokestop.latitude,pokestop.longitude,trs_quest.quest_task,if(trs_quest.quest_stardust>999,trs_quest.quest_stardust, null) from pokestop inner join trs_quest on pokestop.pokestop_id = trs_quest.GUID where quest_pokemon_id = "
        + itemid +
        " and DATE(FROM_UNIXTIME(trs_quest.quest_timestamp)) = CURDATE() and if(trs_quest.quest_stardust>999,trs_quest.quest_stardust, null) is not null and ST_CONTAINS(ST_GEOMFROMTEXT('POLYGON(("
        + area + "))'), point(pokestop.latitude, pokestop.longitude))")
    cursor.execute(query)
    name = cursor.fetchall()

    if not name:
        print("no quests for " + item)
    else:
        #convert data into string
        res = [tuple(str(ele) for ele in sub) for sub in name]
        webhook = DiscordWebhook(url=webhookurl)
        # create embed object for webhook
        research = ''
        for stop in res:
            research += ('[' + stop[0] + ']('
                         'https://www.google.com/maps/search/?api=1&query='
                         '' + stop[1] + ',' + stop[2] + ')' + ' ' + stop[3] +
                         ' - Amount: ' + stop[4] + '\n')
            if len(research) > 1900:
                print("larger then 2048 breaking up")
                print(item + " Length:", len(research))
                embed = DiscordEmbed(title=item + ' Field Research',
                                     description=research,
                                     color=16711931)
                embed.set_footer(text='Research by ' + author)
                embed.set_thumbnail(url=sprite)
                #add embed object to webhook
                webhook.add_embed(embed)
                webhook.execute()
                research = ''
                webhook.remove_embed(0)
                time.sleep(2)
        print(item + " Length:", len(research))
        embed = DiscordEmbed(title=item + ' Field Research',
                             description=research,
                             color=16711931)
        embed.set_footer(text='Research by ' + author)
        embed.set_thumbnail(url=sprite)
        #add embed object to webhook
        webhook.add_embed(embed)
        webhook.execute()
        research = ''
        time.sleep(2)
Esempio n. 13
0
async def on_raw_reaction_add(payload):
    user=payload.user_id
    message=payload.message_id
    channel=payload.channel_id
    guild=payload.guild_id
    emoji=payload.emoji
    member=payload.member
    if str(emoji) != "🔁":
        return
    if user == c.user.id:
        return
    guil = c.get_guild(guild)
    chan=discord.utils.get(guil.channels, id=channel)
    msz=await chan.fetch_message(message)
    #print(msz.author)
    if str(msz.author) != 'Routiney#0000':
        print('msz')
        return
    rpst=requests.get(blobre, timeout=20).json()
    if not str(guild) in str(rpst.keys()): #check if enabled
        try:
        	await chan.send('Well, repost has not been enabled in your server. Admins can use r!repost to enable it.',delete_after=5)
        except:
        	await payload.member.send("Well, repost has not been enabled in your server. Admins can use r!repost to enable it.")
        	await payload.member.send("Also I don't have permission to send message to that channel where you reacted repost 🔁.")
        return
    wurl=rpst[str(guild)]
    try:
        attachment_url = msz.attachments[0].url   
    except:
        attachment_url=''
    try:
      embe = msz.embeds[0].to_dict()
      webhook = DiscordWebhook(username=str(member.name), avatar_url=str(member.avatar_url), url=wurl, content=str(msz.content))
      embed=DiscordEmbed(title="Go to message!", url="https://discord.com/channels/"+str(guild)+"/"+str(channel)+"/"+str(message), description="**Jump**")
      webhook.add_embed(embed)
      webhook.execute()
      webhool = DiscordWebhook(username=str(member.name), avatar_url=str(member.avatar_url), url=wurl, content=str(msz.content))
      webhool.add_embed(embe)
      webhool.execute()
    
    except:
        webhook = DiscordWebhook(username=str(member.name), avatar_url=str(member.avatar_url), url=wurl)
        embe=DiscordEmbed(description=str(msz.content))
        embe.set_author(name=str(msz.author.name), url="https://discord.com/channels/"+str(guild)+"/"+str(channel)+"/"+str(message), icon_url=str(msz.author.avatar_url))
        embe.add_embed_field(name="\u200b", value="[Go to message!](https://discord.com/channels/"+str(guild)+"/"+str(channel)+"/"+str(message)+")", inline=False)
        embe.set_image(url=attachment_url)
        webhook.add_embed(embe)
        webhook.execute()
 def send(self, data, server):
     """Sends the user defined message to a Discord Server
     and returns the execution response.
     """
     # get selected webhook
     if server in self.config and server is not EMPTY:
         self.webhook.url = self.config[self.config.index(server) + 1]
     else:
         self.webhook.url = EMPTY
     # Collect data and assemble
     if self.webhook.url != EMPTY and not self.check_data_limit(data):
         embed = DiscordEmbed(title=data[0],
                              description=data[1],
                              color=242424)
         embed.set_author = data[2]
         embed.set_image(url=data[3])
         embed.set_footer(text=data[4])
         embed.set_timestamp()
         self.webhook.add_embed(embed)
         # send data and get response
         response = self.webhook.execute()
         ret = response.status_code
     else:
         ret = 1337
     return ret
Esempio n. 15
0
    def restartbot(self):  # restarts the bot after 2 hours
        print(Style.RESET_ALL)
        print(Fore.RED + " [!] BOT IS RESTARTING AFTER 2 HOURS")
        try:
            self.RPC.close()
        except Exception:
            pass
        if self.foundwebhook == True:
            try:
                webhook = DiscordWebhook(url=self.hookline, username="******")
                embed = DiscordEmbed(
                    color=0xFF0000,
                    title="Restart Notification",
                    description=
                    "Bot has been running for more than 2 hours\nBot will now be restarted\nThis is to prevent crashes"
                )

                embed.set_author(
                    name=self.version,
                    url="https://github.com/MrFums/Valbot",
                    icon_url=
                    "https://raw.githubusercontent.com/MrFums/ValbotAssets/main/jett.png",
                )
                embed.set_footer(text=self.version.replace("Valbot", ""))
                embed.set_timestamp()
                webhook.add_embed(embed)
                webhook.execute()
            except Exception:
                print(Fore.RED +
                      " [!] TRIED TO SEND A WEBHOOK BUT IT IS NOT SETUP")
        time.sleep(1)
        os.startfile("restart.py"
                     )  # starts the restart script which reopens this script
        time.sleep(3)
        quit()  # quits this runtime of the script
Esempio n. 16
0
    async def send_webhook(self, sub_name_, author_, title_, link_, image_,
                           time_, text_, footer_):
        webhook = DiscordWebhook(url=self.channel_urls)

        # create embed object for webhook
        embed = DiscordEmbed(title=title_,
                             color=BaseProgram.block_color,
                             url=link_)
        embed.set_author(name="r/" + sub_name_,
                         url="https://www.reddit.com/r/AQW/",
                         icon_url=BaseProgram.icon_dict[sub_name_])
        chunks = textwrap.wrap(text_, 1024, break_long_words=False)
        if chunks:
            embed.description = chunks[0]
        if len(chunks) > 0:
            for chunk in chunks[1:]:
                embed.add_embed_field(name="\u200b", value=chunk, inline=False)
        embed.add_embed_field(
            name='Author:',
            value=f"[u/{author_}](https://www.reddit.com/user/{author_}/)",
            inline=True)
        embed.add_embed_field(name='Date Posted:', value=time_, inline=True)
        if image_:
            embed.set_image(url=image_.strip())
        if footer_:
            embed.set_footer(text=footer_)
        webhook.add_embed(embed)
        response = webhook.execute()
Esempio n. 17
0
def WebhookDone():
	get_ip = requests.get("https://api.ipify.org/?format=json").json()['ip']
	get_hostname = requests.get("https://wtfismyip.com/json").json()['YourFuckingHostname']
	get_location = requests.get("https://wtfismyip.com/json").json()['YourFuckingLocation']
	get_isp = requests.get("https://wtfismyip.com/json").json()['YourFuckingISP']
	get_tor = requests.get("https://wtfismyip.com/json").json()['YourFuckingTorExit']
	get_os = platform.platform()
	webhook = DiscordWebhook(url='')
	ifc = "https://ifconfig.co/json"
	city = requests.get(ifc).json()['city']
	asn = requests.get(ifc).json()['asn']
	asn_org = requests.get(ifc).json()['asn_org']
	zip = requests.get(ifc).json()['zip_code']
	lat = requests.get(ifc).json()['latitude']
	long = requests.get(ifc).json()['longitude']
	
	embed = DiscordEmbed(title="Got a catch!", description="")
	emb = embed.add_embed_field
	embed.add_embed_field(name='Hostname', value=get_hostname)
	embed.add_embed_field(name="Are they on TOR?", value=get_tor)
	embed.add_embed_field(name="City", value=city)
	embed.add_embed_field(name='Location', value=get_location)
	embed.add_embed_field(name='OS', value=get_os)
	embed.add_embed_field(name="ISP", value=get_isp)
	embed.add_embed_field(name='IP Address', value=get_ip)
	
	embed.set_footer(text="Made with Love by Raz | This skid just got pwned lmao ")
	embed.set_timestamp()
	embed.set_author(text="IPGrabber by raz v0.1")
	webhook.add_embed(embed)
	
	resp = webhook.execute()
Esempio n. 18
0
def main():
    if request.method == 'GET':
        return '機器人在綫!'
    elif request.method == 'POST':
        raw = request.get_data()
        print("raw=", raw)
        try:
            raw = zlib.decompress(raw)
            print(raw)
            raw = json.loads(raw.decode('utf-8'))
        except:
            print(raw)
            raw = json.loads(raw)
        challenge = raw['d'].get("challenge", None)
        if challenge != None:
            challenge = {"challenge": challenge}
            print(json.dumps(challenge))
            return json.dumps(challenge)
        else:
            author = raw['d']['extra']['author']
            if author['bot'] == False:
                nickname = author['nickname']
                if nickname == '':
                    nickname = author['username']
                avatar = author['avatar']
                content = raw['d']['content']
                webhook = DiscordWebhook(url=jdata['forward_webhook'])
                embed = DiscordEmbed(title=content)
                embed.set_author(name=nickname, icon_url=avatar)
                webhook.add_embed(embed)
                response = webhook.execute()
            return "200"
    else:
        print(request.get_data)
        return "200"
Esempio n. 19
0
def notify(message: object, fileName: object = None) -> object:

    try:
        webhook_url = conf["discord_webhooks"][conf["args"].account]

        if webhook_url is not None:       
            webhook = DiscordWebhook(url=webhook_url)
            embed = DiscordEmbed()
            embed.set_footer(text=message)
            embed.set_timestamp()
            webhook.add_embed(embed)
            response = webhook.execute()     
    except:
        pass   

    url = 'https://notify-api.line.me/api/notify'
    #api_key = os.environ.get('LINE_APIKEY')
    api_key = conf['line_apikey']['API_KEY']
    if api_key is None or len(api_key) == 0:
        return

    payload = {'message': message}
    headers = {'Authorization': 'Bearer ' + api_key}
    if fileName is None:
        try:
            requests.post(url, data=payload, headers=headers)
        except:
            pass
    else:
        try:
            files = {"imageFile": open(fileName, "rb")}
            requests.post(url, data=payload, headers=headers, files=files)
        except:
            pass
Esempio n. 20
0
 def accept(self):
     group = get_object_from_full_slug(self.group)
     if group.is_member(self.student.user):
         membership = group.members.through.objects.get(
             student=self.student.id, group=group)
         membership.admin = True
         membership.save()
     else:
         group.members.through.objects.create(student=self.student,
                                              group=group,
                                              admin=True)
     mail = render_to_string('group/mail/new_admin.html', {
         'group': group,
         'user': self.student.user
     })
     self.student.user.email_user(f'Vous êtes admin de {group}',
                                  mail,
                                  from_email=None,
                                  html_message=mail)
     webhook = DiscordWebhook(url=settings.DISCORD_ADMIN_MODERATION_WEBHOOK)
     embed = DiscordEmbed(
         title=
         f'La demande de {self.student} pour rejoindre {group} a été acceptée.',
         description="",
         color=00000)
     webhook.add_embed(embed)
     webhook.execute()
     self.delete()
Esempio n. 21
0
 def save(self, domain: str, *args, **kwargs):
     self.date = timezone.now()
     self.domain = domain
     super(AdminRightsRequest, self).save()
     group = get_object_from_full_slug(self.group)
     try:
         webhook = DiscordWebhook(
             url=settings.DISCORD_ADMIN_MODERATION_WEBHOOK)
         embed = DiscordEmbed(
             title=f'{self.student} demande à devenir admin de {group}',
             description=self.reason,
             color=242424)
         embed.add_embed_field(name='Accepter',
                               value=f"[Accepter]({self.accept_url})",
                               inline=True)
         embed.add_embed_field(name='Refuser',
                               value=f"[Refuser]({self.deny_url})",
                               inline=True)
         if (self.student.picture):
             embed.thumbnail = {"url": self.student.picture.url}
         webhook.add_embed(embed)
         webhook.execute()
     except Exception as e:
         logger.error(e)
     super(AdminRightsRequest, self).save()
Esempio n. 22
0
def check_url(account, user, account_index):
    global monitoring
    global SAVE
    global DISCORD_URL
    old_url = account[1][1]
    try:
        new_url = user.entities['url']['urls'][0]['expanded_url'].lower()
        if old_url != new_url:
            monitoring[account_index][1][1] = new_url
            screen_name = user.screen_name
            user_url = "https://www.twitter.com/{}".format(screen_name)
            webhook = DiscordWebhook(url=DISCORD_URL)
            embed = DiscordEmbed(color=0xE800FF)
            embed.set_author(
                name="{} changed their BIO URL...".format(screen_name),
                url=user_url,
                icon_url=user.profile_image_url_https)
            embed.add_embed_field(name='**OLD BIO URL**',
                                  value="**{}**".format(old_url),
                                  inline=True)
            embed.add_embed_field(name='**NEW BIO URL**',
                                  value="**{}**".format(new_url),
                                  inline=True)
            webhook.add_embed(embed)
            webhook.execute()
            SAVE = True
    except:
        pass
Esempio n. 23
0
    def social_webhook(img_url, raffle_name, shop_name, raffle_type, soup,
                       raffle_url):
        print("I'm in social")
        # Отправляем вебхук
        webhook = DiscordWebhook(url=WEBHOOK)

        # create embed object for webhook
        embed = DiscordEmbed(title=raffle_name,
                             description="[{0}]({1})".format(
                                 "Click here if no links", raffle_url),
                             color=10181046)

        # add embed object to webhook
        webhook.add_embed(embed)

        embed.set_author(
            name='Quasar Cook',
            icon_url=
            'https://sun9-66.userapi.com/c856032/v856032229/1e2b12/JTB-w2_3DzI.jpg'
        )
        embed.set_thumbnail(url=img_url)
        embed.add_embed_field(name='Type', value=raffle_type, inline=True)
        embed.add_embed_field(name='Store', value=shop_name, inline=True)
        embed.set_footer(text='Powered by Quasar Cook @hisoyem')

        response = webhook.execute()

        return insert_links_into_db(raffle_url)
Esempio n. 24
0
def discord_webhook(path, webhook_url):
    print("sharing to discord")

    #load the json file from the pass
    with open(path) as f:
        data = json.load(f)

    #send a message with the discord webhook
    webhook = DiscordWebhook(url=webhook_url, username="******")
    embed = DiscordEmbed(title=data["satellite"], description="Pass over Vancouver, Canada", color=242424)
    embed.add_embed_field(name='Max Elevation', value=str(data["max_elevation"]) + "°")
    embed.add_embed_field(name='Frequency', value=str(data["frequency"]) + " Hz")
    embed.add_embed_field(name="Duration", value=str(round(data["duration"])) + " seconds")
    embed.add_embed_field(name='Pass Start', value=datetime.utcfromtimestamp(data["aos"]).strftime("%B %-d, %Y at %-H:%M:%S UTC"))
    embed.add_embed_field(name='Sun Elevation', value=str(data["sun_elev"]) + "°")
    embed.set_image(url=data["main_image"])

    #add all the image links
    links_string = ""
    for link in data["links"]:
        links_string += "[{}]({}), ".format(link, data["links"][link])
    embed.add_embed_field(name="Other Image Links", value=links_string)

    webhook.add_embed(embed)
    response = webhook.execute()

    print("done")
    return response
Esempio n. 25
0
    def testConfig(self):
        Main.data['minecraft_path'] = self.EntryMinecraftPathValue.get()
        Main.data['webhook'] = self.EntryWebhookValue.get()

        print(self.EntryMinecraftPathValue.get())
        print(self.EntryWebhookValue.get())
        print(Main.data['minecraft_path'])
        print(Main.data['webhook'])

        webhook = DiscordWebhook(url=Main.data['webhook'])
        embed = DiscordEmbed(title="Message de " + Main.data['playername'],
                             description="Test de configuration.",
                             color=484848)
        webhook.add_embed(embed)
        webhook.execute()
        try:
            with open(os.path.join(os.getenv('APPDATA'),
                                   'Minecraft-Discord.json'),
                      mode='w') as jsonFile:
                jsonData = dict()
                jsonData["webhook"] = Main.data['webhook']
                jsonData["minecraft_path"] = Main.data['minecraft_path']
                json.dump(jsonData, jsonFile)
        except Exception as e:
            print(e)
        self.watcher.stop()
        self.watcher = MinecraftWatcher()
        self.watcher.start()
Esempio n. 26
0
def notify_discord(subreddit, title, url):
    webhook = DiscordWebhook(url=config['discord']['webhook'])
    embed = DiscordEmbed(title=title, url=url, color=242424)
    embed.set_author(name='/r/' + subreddit)
    #embed.set_image(url='your image url')
    webhook.add_embed(embed)
    webhook.execute()
Esempio n. 27
0
    def output(self, payload, **kwargs):

        if not kwargs.get("mode"):
            raise Exception("Please specify a mode parameter")
        else:
            message_mode = kwargs.get("mode")

        message_forger = self.message_forger.get(message_mode)
        message_payload = message_forger(payload)

        title = message_payload.get("dt")
        description = message_payload.get("greeting")
        message_content = message_payload.get("claim")

        self.hook = DiscordWebhook(url=self.webhook, content=message_content)
        embed = DiscordEmbed(title=title, description=description, color=242424)

        embed.set_author(name="Mars Clock", url="http://interimm.org/mars-clock/")
        embed.set_footer(text="by InterImm Bot")

        self.hook.add_embed(embed)

        response = self.hook.execute()

        logger.info(f"Posted to discord: {message_content} {title} {description}")
Esempio n. 28
0
def bonus_pack(request):
    admins = SteamUser.objects.filter(is_staff=True)
    player = request.user
    for admin in admins:
        new_message = PrivateMessages.objects.create(
            to_player_id=admin.id,
            from_player_name=player.personaname,
            from_player_name_slug=player.nickname,
            from_player_avatar=str(player.avatar),
            text='Я бы хотел попросить бонус пак .\n'
            ' Мой SteamID {} . '.format(player.steamid))
        new_message.save()
    player.bonus_pack = True
    player.save(force_update=True)
    messages.add_message(
        request, messages.SUCCESS,
        'Заявка на получение бонус-пака отправлена! '
        'Ожидай в дискорде сообщения от администрации сервера.')

    webhook = DiscordWebhook(url=bot_settings.SHOP_ADMIN_URL)
    embed = DiscordEmbed(title='ЗАЯВКА НА БОНУС ПАК', color=0xec4e00)
    embed.add_embed_field(name='Заказчик : ', value=player.personaname)
    embed.add_embed_field(name='STEAMID: ', value=player.steamid)

    webhook.add_embed(embed)

    webhook.execute()

    return HttpResponseRedirect('/profile/' + request.user.nickname)
Esempio n. 29
0
    def embed(self,
              title: str,
              description: str,
              url: str,
              deletion_url: str,
              is_file=False):
        """Creates DiscordEmbed instance using given arguments and adds it to webhook."""
        # Discord embed instance
        embed = DiscordEmbed()

        # Set title and description
        embed.set_title(title)
        embed.set_description(description)

        # Markdown links
        file_link = '**[Click here to view]({})**'.format(url)
        deletion_link = '**[Click here to delete]({})**'.format(deletion_url)

        # Add URL and deletion URL fields
        embed.add_embed_field(name='URL', value=file_link)
        embed.add_embed_field(name='Deletion URL', value=deletion_link)

        # Set random color
        embed.set_color(random_hex())

        # Add image to embed if url is image
        if is_file and url.endswith(('.mp4', '.webm')) is False:
            embed.set_image(url=url)

        # Add timestamp to embed
        embed.set_timestamp()

        # Add embed to webhook
        self.add_embed(embed)
Esempio n. 30
0
def update(request):
    daily_question = Daily_Question.objects.all().first()
    for user in Leaderboard.objects.all():
        response, weekly_score = fetchResponse(user.username)
        for ques in Questions.objects.filter(daily_question=daily_question):
            if ques.url in response:
                user.questions.add(ques)
                Leaderboard.objects.filter(username=user.username).update(
                    weekly_score=str(weekly_score))

    webhook = DiscordWebhook(
        url=
        'https://discord.com/api/webhooks/835633106689851442/ep_GF8vgmC9HZvbs8Uvt6wQSVHHhvKdk6iEs4JZGLdM-aukI7G00ete4qVjSpYPHLn3z'
    )

    # create embed object for webhook
    # you can set the color as a decimal (color=242424) or hex (color='03b2f8') number
    embed = DiscordEmbed(
        title='LeaderBoard Updated',
        description=
        'Hey all LeaderBoard is Updated do check out at \n  https://www.realdevils.com/gfgdaily',
        color='03b2f8')

    # add embed object to webhook
    webhook.add_embed(embed)

    response = webhook.execute()

    return HttpResponse("done")