def start_bot(): degree_sign = u'\N{DEGREE SIGN}' url = 'https://discordapp.com/api/webhooks/123453/12345654' link = "http://192.xxx.x.xxx:42000/getstat" r = requests.get(url=link) data = json.loads(r.text) uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(int(data['start_time'])))[:-7] gpuTxt = "" totalSpeed = 0 totalWatt = 0 for gpu in data['result']: gpuTxt += "\t{} : {}{}C {}W {}Sol/s\n".format( str(gpu['gpuid']), str(gpu['temperature']), degree_sign, str(gpu['gpu_power_usage']), str(gpu['speed_sps'])) totalSpeed += gpu['gpu_power_usage'] totalWatt += gpu['speed_sps'] if gpu['temperature'] >= 90: tempCheck(gpu['temperature']) msgTxt = "```css\n{}Sol/s {}W\n--------------\nServer: {}\nUptime: {}\nGPU's:\n{}\n```".format( str(totalWatt), str(totalSpeed), data['current_server'], str(uptime), gpuTxt) msg = Webhook(url, msg=msgTxt) msg.post()
def callback(update): if type(update) is UpdateNewChannelMessage: try: logger.debug(update) if update.message.to_id.channel_id == channel_id: logger.info("Relaying Message from Channel ID: {}".format( update.message.to_id.channel_id)) if update.message.id > lastmessage: lastmessage = update.message.id logger.debug("Last message is now " + str(lastmessage)) if not update.message.message == '': if everyone: msgText = "*{}*: @everyone {}".format( channel_name, update.message.message) else: msgText = "*{}*: {}".format(channel_name, update.message.message) msg = Webhook(url, msg=msgText) msg.post() else: logger.debug('ignoring empty message: {}'.format( update.message)) else: logger.info("Ignoring Message from Channel ID: {}".format( update.message.to_id.channel_id)) except: logger.debug('no message')
def write2file(self, text): if self.webhookurl: msg = Webhook(self.webhookurl, msg=str(text)) msg.post() with self.lock: with open(self.filename, 'a') as file: file.write(text)
def post_to_webhook(self, slug): post = self.get_post_from_server(slug) msg_string = (post['body'][:250] + '...') if len(post['body']) > 250 else post['body'] embed = Webhook(HOOK_URL, color=123123) embed.set_author(name=post['title'], icon='https://cdn6.aptoide.com/imgs/5/1/f/51fc6f8666c50ce7456651810d7a4439_icon.png?w=240') embed.set_desc(msg_string) embed.add_field(name='Read more', value=post['url']) embed.post()
def post_to_discord(event, webhook): msg_text = event.text # event.raw_text url_reg = r'(https?[:.]+[^\s\)]+)' msg_text = re.sub(url_reg, r'<\1>', msg_text) msg = Webhook(webhook, msg=msg_text) msg.post() #print(event.input_sender, event.document, event.text) logger.info('Delivered to webhook %s' % (webhook))
def check_system(name): reports = [] system_report = [] edsm_id = solar_system.get_by_name(name) system = solar_system.get(edsm_id) if system is None: return None factions = solar_system.get_factions(edsm_id) add_report = False for this_faction in factions: local_faction = faction.get(this_faction[1]) if local_faction[1] not in records[name].keys(): records[name][local_faction[1]] = this_faction[2] prev = records[name][local_faction[1]] current = this_faction[2] if prev is not None: # Status change. if prev < current: move = 'increased' direction = ':arrow_up_small:' else: move = 'decreased' direction = ':small_red_triangle_down:' # Is this our faction? if settings.owners[name] == local_faction[1]: home_faction = ':EliteSmile:' else: home_faction = '' prev_percent = '{:.1%}'.format(float(prev)) current_percent = '{:.1%}'.format(float(current)) if prev != current: # System we are looking at. current_system = solar_system.get(edsm_id) system_name = current_system[1] records[name][local_faction[1]] = this_faction[2] add_report = True if settings.owners[name] == local_faction[1]: system_report.insert( 0, '**' + local_faction[1] + '** influence in __' + system_name + '__ has ' + move + ' from ' + prev_percent + ' to ' + current_percent) faction_percent = '{:.1%}'.format(float(this_faction[2])) system_report.append("* " + local_faction[1] + home_faction + " (" + this_faction[3] + ") : " + faction_percent + direction) if add_report: reports.append("\n".join(system_report)) description = '' system_report = [] if len(reports) > 0: post = Webhook(settings.webhook_url_system_monitor, msg="\n\n".join(reports)) post.post() print "\n\n".join(reports) print "\n\n" reports = []
def check_faction(name): reports = [] minor_faction_id = faction.get_by_name(name) system_ids = faction.get_systems(minor_faction_id) for edsm_id in system_ids: system_report = [] system = solar_system.get(edsm_id) if system[1] not in records[name].keys(): system_report.append('**' + name + '**d influence in ' + system[1] + ' has changed.') records[name][system[1]] = {} factions = solar_system.get_factions(edsm_id) add_report = False for this_faction in factions: local_faction = faction.get(this_faction[1]) if local_faction[1] not in records[name][system[1]].keys(): records[name][system[1]][local_faction[1]] = this_faction[2] prev = records[name][system[1]][local_faction[1]] current = this_faction[2] # Status change. if prev < current: move = 'increased' direction = ':arrow_up_small:' else: move = 'decreased' direction = ':small_red_triangle_down:' prev_percent = '{:.1%}'.format(float(prev)) current_percent = '{:.1%}'.format(float(current)) if name == local_faction[1] and prev != current: # System we are looking at. current_system = solar_system.get(edsm_id) system_name = current_system[1] system_report.insert(0, '**' + local_faction[1] + '** influence in __' + system_name + '__ has ' + move + ' from ' + prev_percent + ' to ' + current_percent) records[name][system[1]][local_faction[1]] = this_faction[2] add_report = True faction_percent = '{:.1%}'.format(float(this_faction[2])) system_report.append("* " + local_faction[1] + " (" + this_faction[3] + ") : " + faction_percent + direction) if add_report: reports.append("\n".join(system_report)) description = '' system_report = [] if len(reports) > 0: post = Webhook(settings.webhook_url,msg="\n\n".join(reports)) post.post() print "\n\n".join(reports) print "\n\n" reports = []
def tweet_image(skin_name, md5, skin_url, screenshot_path, dry): # Trick Twitter into keeping the skin a PNG img = Image.open(screenshot_path) img = img.convert("RGBA") # ensure 32-bit [w, h] = img.size pixels = img.load() # set bottom-right pixel to 254 alpha pixels[w - 1, h - 1] = pixels[w - 1, h - 1][:3] + (243, ) # Resize to 2x so that pixels remain a bit more crisp when resized w, h = (2 * w, 2 * h) img = img.resize((w, h), 0) img.save(screenshot_path) escaped_skin_url = urllib.parse.quote(skin_url) winamp2_js_url = "https://webamp.org/?skinUrl=%s" % escaped_skin_url status_message = """%s Try Online: %s Download: %s""" % ( skin_name, winamp2_js_url, skin_url, ) if not dry: url = tweet(status_message, screenshot_path) Webhook(CONFIG["discord_url"], msg=url).post() append_line("tweeted.txt", md5) else: print("Would have tweeted: %s" % status_message) print("With media file: %s" % screenshot_path) print("Done!")
def tweet_image(skin_name, md5, skin_url, screenshot_path, double): # Trick Twitter into keeping the skin a PNG img = Image.open(screenshot_path) img = img.convert("RGBA") # ensure 32-bit [w, h] = img.size pixels = img.load() # set bottom-right pixel to 254 alpha pixels[w - 1, h - 1] = pixels[w - 1, h - 1][:3] + (243, ) # Resize to 2x so that pixels remain a bit more crisp when resized if double: w, h = (2 * w, 2 * h) img = img.resize((w, h), 0) img.save(screenshot_path) options = {"skinUrl": skin_url} options_query = urllib.parse.quote(json.dumps(options)) winamp2_js_url = "https://webamp.org/#%s" % options_query status_message = """%s Try Online: %s Download: %s""" % (skin_name, winamp2_js_url, skin_url) if not dry: url = tweet(status_message, screenshot_path) Webhook(CONFIG["discord_url"], msg=url).post() dispatch({"type": "TWEETED", "md5": md5, "message": status_message}) else: print("Would have tweeted: %" % status_message) print("With media file: %" % screenshot_path) print("Done!")
async def handler(update): #prints peer ids of channels result = await client.get_dialogs() print("\n List of channels:") for p in result: print(str(utils.resolve_id(p.id)[0]) + ": " + p.name) try: if str(update.message.to_id.channel_id) in channels: m = update.message media = m.media reply_msg = await m.get_reply_message() if reply_msg is None: text = "{}\n".format(m.message) else: text = "```REPLIED_TO:\n{}```{}\n".format( reply_msg.message, m.message) if media is not None and utils.get_extension(media) == '.jpg': logger.info("Will download image") download_res = await client.download_media( media, './downloads/') logger.info("Download done: {}".format(download_res)) url = img_cli.upload_from_path(download_res, anon=True)['link'] text += url + "\n" os.remove(download_res) logger.debug("File deleted") if not text == '': date = m.date.astimezone(timezone('Asia/Ulaanbaatar')) text += "`" + date.strftime("%Y-%m-%d %H:%M:%S GMT%Z") + "`\n" text += "==================================\n" msg = Webhook(channels[str(m.to_id.channel_id)], msg=text) msg.post() logger.info("Relaying Message from Channel ID: {}".format( update.message.to_id.channel_id)) else: logger.debug('Ignoring empty message: {}'.format( update.message)) else: logger.info("Ignoring Message from Channel: {}: {}".format( update.message.to_id.channel_id, update.message.to_id.channel_name)) except: logger.debug('Exception occurred while handling:\n') logger.debug(update)
def __init__(self, date=datetime.datetime.now().strftime("%d/%m/%Y")): self.bosses = {} self.date = date self.placeholder_icon = "<:FeelsDeadMan:446396105077424138>" self.iconmap = {"Vale Guardian": "<:vale_guardian:449838205701718016>", "Gorseval": "<:gorseval:449838206179868672>", "Sabetha": "<:sabetha:449838205118971909>", "Slothasor": "<:sloth:449838206045913098>", "Matthias": "<:matthias:449838206054170645>", "Keep Construct": "<:keep_construct:449838205731340290>", "Xera": "<:xera:449838206100176896>", "Cairn": "<:cairn:449838199523639307>", "Mursaat Overseer": "<:mursaat_overseer:449838206310023168>", "Samarog":"<:samarog:449838206205296650>", "Deimos": "<:deimos:449838200295391232> ", "Soulless Horror": "<:soulless_horror:449838201943621632>", "Dhuum":"<:dhuum:449838200999903232>"} self.iconmap2 = {"Vale Guardian": "<:vale_guardian:449831911993507850>", "Gorseval": "<:gorseval:449831912190771210>", "Sabetha": "<:sabetha:449831912006221824>", "Slothasor": "<:sloth:449831912064679946>", "Matthias": "<:matthias:449831912177926144>", "Keep Construct": "<:keep_construct:449831911674740737>", "Xera": "<:xera:449831911754432513>", "Cairn": "<:cairn:449831905186283551>", "Mursaat Overseer": "<:mursaat_overseer:449831912123400204>", "Samarog":"<:samarog:449831912526315520>", "Deimos": "<:deimos:449831906188591114>", "Soulless Horror": "<:soulless_horror:449831907509796878>", "Dhuum":"<:dhuum:449831907530899476>"} #{"hook_url1":} self.hook_url1 = "" #this is the testserver self.hook_url2 = "" # this is the dps report channel self.hook_url = self.hook_url2 self.embed = Webhook(self.hook_url, color=0x483768) self.embed.set_desc("__***[Meta] Raid Run on "+self.date+"***__") self.embed.set_thumbnail("https://wiki.guildwars2.com/images/9/9d/Epidemic.png") self.embed.set_footer(text="Participants: Some people", ts=False)
def main(dry): approved = get_lines("approved.txt") tweeted = get_lines("tweeted.txt") candidates = list(set(approved) - set(tweeted)) number_of_potentials = len(candidates) print("Found %s approved skins" % number_of_potentials) if number_of_potentials <= 10: msg = "I'm down to only %s approved skins to tweet. You should review some more." % number_of_potentials Webhook(CONFIG["discord_url"], msg=msg).post() if not number_of_potentials: print("Exiting") return tweet_skin(candidates[0])
def main(argv): global changelist_icon webhook_url = P4_COMMITS_WEBHOOK_URL change = -1 discord_userid = '-1' # Retrieve input arguments try: opts, args = getopt.getopt(argv, "tc:") except getopt.GetoptError: print( "Invalid arguments! -c ChangeNumber -t (to use TEST_WEBHOOK_URL)") sys.exit(2) for opt, arg in opts: if opt == '-c': change = arg if opt == '-t': webhook_url = TEST_WEBHOOK_URL # If no change was given, simply exit if change == -1: print("No change number supplied!") sys.exit(3) # Function will get description and user info about this change and store in a dictionary change_data = get_change_data(change, P4PORT, P4LOGIN, P4PASS) # Match Perforce user from perforce change info to actual Discord user using pre-set dictionaries discord_userid = discord_userids[change_data["user"]] discord_username = discord_usernames[change_data['user']] # Set up and send the embed embed_title = u'Change %s \u2022 %s (%s) \u2022 %s' % ( change, change_data['user'], discord_username, change_data['client']) embed_description = '%s' % (change_data['desc']) message = Webhook(webhook_url, color=0x10b1df) message.set_author( name=embed_title, icon=changelist_icon ) # Author field is used for smaller/more compact font and inline icon message.set_desc(embed_description) message.post()
def proccess_new_post(post): global max_post_id # check for new post if int(post['id']) <= max_post_id: return max_post_id = int(post['id']) # search for photos in attachments photos = [] for atch in post.get('attachments', []): if atch.get('type') == 'photo': photo = atch.get('photo', {}) photo_urls = [i for i in photo.keys() if i.startswith('photo_')] photo_urls.sort(key=lambda x: -int(x.split('_')[-1])) if photo_urls and photo_urls[0]: photos.append(photo[photo_urls[0]]) # generate text msg = post.get('text', '') # add all photos links from attachments. COMMENTED if False: msg += '\n' for i in photos: msg += '\n' + i # create Webhook object wh = Webhook(config['discord_webhook_url'], msg=msg) wh.set_footer(text='https://vk.com/wall-{}_{}'.format( config['vk_group_id'], post['id']), ts=time.time()) # set image if photos: wh.set_image(photos[0]) # send Webhook to discord server wh.post()
def push_data_to_discord_webhook(data, webhookid, webhookkey): """[summary] Pushes data to discord web-hook Arguments: data {[dictionary]} -- [data] webhookid {[string]} -- [webhook id] webhookkey {[string]} -- [key] """ if data != None: url = 'https://discordapp.com/api/webhooks/{}/{}'.format( webhookid, webhookkey) content = "Price {} \nLast Update {} \nChange {}".format( data['price'], data['lastupdate'], data['change']) msg = Webhook(url, msg=content) msg.add_field(name="Field", value='Test Text') msg.post()
def error_hooking(base, type): url = "<WEBHOOK>" embed = Webhook(url, color=123123) embed.set_desc(type.strip(':')) embed.add_field(name="Link", value=base) embed.add_field(name="Error", value="Can't get this product. Please contact with developer") embed.set_footer(text='Powered by <COMPANY NAME>', ts=True,icon='<ICON>') embed.post()
class cRaidclear(): def __init__(self, date=datetime.datetime.now().strftime("%d/%m/%Y")): self.bosses = {} self.date = date self.placeholder_icon = "<:FeelsDeadMan:446396105077424138>" self.iconmap = {"Vale Guardian": "<:vale_guardian:449838205701718016>", "Gorseval": "<:gorseval:449838206179868672>", "Sabetha": "<:sabetha:449838205118971909>", "Slothasor": "<:sloth:449838206045913098>", "Matthias": "<:matthias:449838206054170645>", "Keep Construct": "<:keep_construct:449838205731340290>", "Xera": "<:xera:449838206100176896>", "Cairn": "<:cairn:449838199523639307>", "Mursaat Overseer": "<:mursaat_overseer:449838206310023168>", "Samarog":"<:samarog:449838206205296650>", "Deimos": "<:deimos:449838200295391232> ", "Soulless Horror": "<:soulless_horror:449838201943621632>", "Dhuum":"<:dhuum:449838200999903232>"} self.iconmap2 = {"Vale Guardian": "<:vale_guardian:449831911993507850>", "Gorseval": "<:gorseval:449831912190771210>", "Sabetha": "<:sabetha:449831912006221824>", "Slothasor": "<:sloth:449831912064679946>", "Matthias": "<:matthias:449831912177926144>", "Keep Construct": "<:keep_construct:449831911674740737>", "Xera": "<:xera:449831911754432513>", "Cairn": "<:cairn:449831905186283551>", "Mursaat Overseer": "<:mursaat_overseer:449831912123400204>", "Samarog":"<:samarog:449831912526315520>", "Deimos": "<:deimos:449831906188591114>", "Soulless Horror": "<:soulless_horror:449831907509796878>", "Dhuum":"<:dhuum:449831907530899476>"} #{"hook_url1":} self.hook_url1 = "" #this is the testserver self.hook_url2 = "" # this is the dps report channel self.hook_url = self.hook_url2 self.embed = Webhook(self.hook_url, color=0x483768) self.embed.set_desc("__***[Meta] Raid Run on "+self.date+"***__") self.embed.set_thumbnail("https://wiki.guildwars2.com/images/9/9d/Epidemic.png") self.embed.set_footer(text="Participants: Some people", ts=False) def set_bosses(self, bosses): """bosses is a dict that containts the bosses + links """ self.bosses = bosses def add_bossfields(self): for key in self.bosses.keys(): self.embed.add_field(name=self.iconmap.get(key, self.placeholder_icon)+key, value="[dps.report]("+self.bosses[key]+" \""+self.bosses[key]+"\")") def post_to_discord(self): #self.embed.set_desc("I am a descriptive description describing in a descriptive way.") self.embed.set_author(name="Chrononono") self.embed.post() def test_message(self): test_message = self.embed test_message.add_field(name="This is a test!", value="Nothing to see here") test_message.set_desc("A very inconspicuous message") test_message.set_author(name="Rogue AI") test_message.set_footer(text="This is the last test, I promise!", ts=False) test_message.post()
def send_embed(alert_type, link, fields, site, image, product): ''' (str, str, list, str, str, str) -> None Sends a discord alert based on info provided. ''' url = webhook embed = Webhook(url, color=123123) if (alert_type == "NEW_SHOPIFY"): desc = "NEW: " + product elif (alert_type == "RESTOCK_SHOPIFY"): desc = "RESTOCK: " + product embed.set_author( name='NERYS', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg') embed.set_desc(desc) for field in fields: if (alert_type == "NEW_SHOPIFY" or alert_type == "RESTOCK_SHOPIFY"): cart_link = site + "/cart/" + str(field[1]) + ":1" embed.add_field(name=str(field[0]), value=cart_link) if (image is not None): embed.set_thumbnail(image) embed.set_image(image) embed.set_footer( text='NERYS by @snivynGOD', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg', ts=True) embed.post()
def send_embed(alert_type, link, fields, site, image, product): ''' (str, str, list, str, str, str) -> None Sends a discord alert based on info provided. ''' url = webhook embed = Webhook(url, color=123123) if (alert_type == "NEW_SHOPIFY"): desc = "NEW: " + product elif (alert_type == "RESTOCK_SHOPIFY"): desc = "RESTOCK: " + product embed.set_author( name='ARB', icon= 'https://sun9-74.userapi.com/impf/x8e2VAfW-ao86OPcoUeSKpB7sup-dlIC3bT-2g/I3Vwk9su7D8.jpg?size=564x532&quality=96&sign=423037df9ddf5c5400c93844710086c3&type=album' ) embed.set_desc(desc) for field in fields: if (alert_type == "NEW_SHOPIFY" or alert_type == "RESTOCK_SHOPIFY"): cart_link = site + "/cart/" + str(field[1]) + ":1" embed.add_field(name=str(field[0]), value=cart_link) if (image is not None): embed.set_thumbnail(image) embed.set_image(image) embed.set_footer( text='ARB by @JaqueFresco', icon= 'https://sun9-11.userapi.com/impf/DagUwT61wIcd0BeLtPOI3UFtf2nV2ZK9Gh-8NQ/ehNPfNbLWGA.jpg?size=754x750&quality=96&sign=ce4bfc72ef8fdcfbbf3c11dbd8589382&type=album', ts=True) embed.post()
def send_embed(alert_type, product): ''' (str, str, list, str, str, str) -> None Sends a discord alert based on info provided. ''' # Set webhook url = discord_webhook # Create embed to send to webhook embed = Webhook(url, color=123123) # Set author info embed.set_author( name='Nike', icon= 'https://static-breeze.nike.co.kr/kr/ko_kr/cmsstatic/theme/52/android-icon-36x36.png' ) # Set product details if (alert_type == "RESTOCK"): embed.set_desc("RESTOCK: " + "title") elif (alert_type == "NEW"): embed.set_desc("NEW: " + product.title) # Name, Code, Color, Date, Price # Early Link # Time embed.add_field(name="Name", value=product.name) embed.add_field(name="Code", value=product.code) embed.add_field(name="Color", value=product.color) embed.add_field(name="Price", value=product.price) embed.add_field(name="Link", value=product.siteLink) embed.add_field(name="Time", value=product.pTime) embed.add_field(name="ImgLink", value=product.imgLink) # Set product image embed.set_thumbnail(product.imgLink) embed.set_image(product.imgLink) # Set footer embed.set_footer( text='Nike by @DevHong', icon= 'https://static-breeze.nike.co.kr/kr/ko_kr/cmsstatic/theme/52/android-icon-36x36.png', ts=True) # Send Discord alert embed.post()
def EmbedMsg(): global Author global AuthorID global Title global Banner global RankedLink global Length global BPM global GMFormat global GMFormat2 embed = Webhook(webhook, color=0x0098f9) embed.set_author(name='New {} map by {}'.format(GMFormat, Author), icon='https://a.ppy.sh/{}'.format(AuthorID), url='https://osu.ppy.sh/users/{}'.format(AuthorID)) embed.set_title(title='**__{}__**'.format(Title),url=RankedLink) embed.set_thumbnail(Banner) embed.set_desc("""**BPM:** {} **Song Length:** {} **Containing:** {} """.format(BPM, Length, GMFormat2)) embed.set_footer(text='Ranked!',ts=True,icon='https://hypercyte.s-ul.eu/W4GBjy0M') embed.post() NewRanked()
def send_embed(product): ''' (Product) -> None Sends a discord alert based on info provided. ''' url = 'https://discordapp.com/api/webhooks/609541516377194508/nJqkl98mdg9SvlF0pIZmJ-YY8EePCwQdfLJ-4oB4WJj3WR6Ve0LpzFZGHcOLrvDyxrAT' embed = Webhook(url, color=123123) embed.set_author( name='NERYS', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg') embed.set_desc("Found product based on keyword " + product.keyword) embed.add_field(name="Link", value=product.link) embed.set_footer( text='NERYS by @snivynGOD', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg', ts=True) embed.post()
def webhook(link, currency, photo, title, description, ino): link = 'https://www.supremenewyork.com' + link.rstrip() url = "<WEBHOOK>" embed = Webhook(url, color=123123) embed.set_desc("RESTOCK: [{0}]({1})".format(title, link)) embed.add_field(name="Description", value=description) embed.add_field(name="Ino", value=ino) embed.add_field(name="Currency", value=currency) embed.add_field(name="Link", value=link) embed.set_thumbnail(photo) embed.set_footer(text='Powered by <COMPANY NAME>', ts=True, icon='<FOOTER ICON>') embed.post()
def runTestsAndUploadResultsToDb(gameReturn, EditorReturn): functionDict = {} if (not gameReturn and not EditorReturn): try: with open( "C:\\Program Files (x86)\\Jenkins\\workspace\\SSP\\thomas\\CompiledGame\\Bin\\data.json", "r") as ins: data = json.load(ins) function_data = {} for processor_id in data["SlowfilerData"]["processor"]: for function in data["SlowfilerData"]["processor"][ processor_id]["functions"]: rawData = [ int(s) for s in data["SlowfilerData"]["processor"] [processor_id]["functions"][function].split(',') ] rawData = [x / 1000000.0 for x in rawData ] # Gives an array of all samples function_data[function] = {} function_data[function]["avg"] = sum(rawData) / len( rawData) try: function_data[function]["std"] = statistics.stdev( rawData) except statistics.StatisticsError: print( "Only one entry for {}, cannot calculate varience". format(function)) function_data[function]["std"] = 0 function_data[function]["max"] = max(rawData) function_data[function]["min"] = min(rawData) array = np.array(rawData) function_data[function]["97th"] = np.percentile(array, 97) # parse all fps samples from json object fps_samples_cpu = [ x / 1000000 for x in data["SlowfilerData"]["build"]["fps"][::10] ] fps_samples_gpu = [ x / 1000000 for x in data["SlowfilerData"]["gpu"][::10] ] # fetch all jenkins data # We are going to assume that we have the data of the latest job j = jenkins.Jenkins("http://192.168.1.141:8080", "admin", "jenkinsjenkar") job = j.get_job_info("SSP") # All info from job SSP build_number = job["lastBuild"]["number"] # build_duration = j.get_build_info( "SSP", job["lastBuild"]["number"])[ "duration"] # Fetch duration of latest build # Connect to database sqlite_file = 'C:\\test.db' conn = sqlite3.connect(sqlite_file) c = conn.cursor() for sample in fps_samples_cpu: # For every function, send data to database try: table_name = 'Build_fps_gpu' column_sample = 'sample' column_build = 'build' c.execute("INSERT INTO {tn} ({cs}, {cb}) VALUES ({vs}, {vb})".\ format(tn=table_name, cs=column_sample, cb=column_build, vs=sample, vb=build_number)) except sqlite3.IntegrityError: print('ERROR: ID already exists in PRIMARY KEY column {}'. format(id_column)) for sample in fps_samples_gpu: # For every function, send data to database try: table_name = 'Build_fps_cpu' column_sample = 'sample' column_build = 'build' c.execute("INSERT INTO {tn} ({cs}, {cb}) VALUES ({vs}, {vb})".\ format(tn=table_name, cs=column_sample, cb=column_build, vs=sample, vb=build_number)) except sqlite3.IntegrityError: print('ERROR: ID already exists in PRIMARY KEY column {}'. format(id_column)) for function in function_data: # For every function, send data to database try: table_name = 'Function_build' column_name = 'function_name' column_avg = 'avg' column_std = 'std' column_max = 'max' column_min = 'min' column_build = 'build' column_97th = 'p97th' sample = function_data[function] c.execute("INSERT INTO {tn} ({cn}, {ca}, {cs}, {cm}, {cnv}, {cb}, {c97}) VALUES (\"{vn}\", {va}, {vs}, {vm}, {vnv}, {vb}, {v97})".\ format(tn=table_name, cn=column_name, ca=column_avg, cs=column_std, cm=column_max, cnv=column_min, cb=column_build, c97=column_97th, vn=function, va=(sample["avg"]), vs=sample["std"], vm=sample["max"], vnv=sample["min"], vb=build_number, v97=sample["97th"])) except sqlite3.IntegrityError: print('ERROR: ID already exists in PRIMARY KEY column {}'. format(id_column)) try: table_name = 'Build_data' column_number = "build_number" column_duration = "build_time_duration" column_ramusage = "build_ramusage" column_vramuasge = "build_vramusage" column_avgfps = "build_avgfps" column_minfps = "build_minfps" column_stdfps = "build_stdfps" c.execute("INSERT INTO {tn} ({cn}, {cd}, {cr}, {cv}, {cavgfps}, {cminfps}, {cstdfps}) VALUES ({vn}, {vd}, {vr}, {vv}, {vavgfps}, {vminfps}, {vstdfps})".\ format(tn=table_name, cn=column_number, cd=column_duration, cr=column_ramusage, cv=column_vramuasge, cavgfps=column_avgfps, cminfps=column_minfps, cstdfps=column_stdfps, vn=build_number, vd=build_duration, vr=data["SlowfilerData"]["build"]["ramUsage"], vv=data["SlowfilerData"]["build"]["vramUsage"], vavgfps=sum(fps_samples_cpu) / len(fps_samples_cpu), vminfps=min(fps_samples_cpu), vstdfps=statistics.stdev(fps_samples_cpu))) except sqlite3.IntegrityError: print( 'ERROR: ID already exists in PRIMARY KEY column {}'.format( id_column)) # Close connection conn.commit() conn.close() embed = Webhook(url, color=428644) ram_usage = data["SlowfilerData"]["build"]["ramUsage"] vram_usage = data["SlowfilerData"]["build"]["vramUsage"] avg_fps = sum(fps_samples_cpu) / len(fps_samples_cpu) embed.set_author(name='Slowfiler', icon='https://i.imgur.com/rdm3W9t.png') embed.set_desc( 'New preformance report available at http://192.168.1.141:8069/builds/ ' ) embed.add_field(name='Average frametime:', value="{} ms".format(avg_fps)) embed.add_field(name='RAM USAGE:', value="{} mb".format(ram_usage - vram_usage)) embed.add_field(name='VRAM USAGE:', value="{} mb".format(vram_usage)) if (ram_usage - vram_usage) < 256 and vram_usage < 512 and avg_fps < 32: embed.add_field(name='STATUS:', value="PASS") else: embed.add_field(name='STATUS:', value="FAIL") embed.set_thumbnail( 'https://t4.rbxcdn.com/fee318796364847e0ff53ea658490477') embed.set_footer(text='Slowfiler, copyright 3-D asset', ts=True) embed.post() return 0 except IOError: print("Could not open file") return -1 else: embed = Webhook(url, color=428644) embed.set_author(name='Slowfiler', icon='https://i.imgur.com/rdm3W9t.png') embed.set_desc('Could not run game or editor ') if (not gameReturn): embed.add_field(name='GAME STATUS:', value="FAIL") if (not EditorReturn): embed.add_field(name='EDITOR STATUS:', value="FAIL") embed.set_thumbnail( 'https://t4.rbxcdn.com/fee318796364847e0ff53ea658490477') embed.set_footer(text='Slowfiler, copyright 3-D asset', ts=True) embed.post() return -1
from discord_hooks import Webhook from datetime import datetime WEBHOOK_URL = '' embed = Webhook( url=WEBHOOK_URL, username='******', # Username of the 'bot' color=555553, # Colour of the side of the embed ) def sendHook(prodtitle, url, dateTimeObj): embed.set_author(name=prodtitle, url=url) embed.set_title(title=prodtitle, url=url) embed.set_desc("``` YOU CAN F*****G BUY IT NOW RUDE BOI```" + url) #embed.add_field(name="Field 1 \U0001f603", value="some of these properties have certain limits...", inline=False) #embed.add_field(name="Field 2 :scream:", # value="try exceeding some of them!", inline=False) #embed.add_field(name="Field 3 :face_with_rolling_eyes:", value="Jokes, dont do that.", inline=False) #embed.add_field(name="Field 4 :face_with_rolling_eyes:", value="these last two") #embed.add_field(name="Field 5 :face_with_rolling_eyes:", value="are inline fields") ## Set the timestamp to either a ISO 8601 timestamp, or simply use `now=True`, which uses current time embed.set_timestamp(time=str(dateTimeObj)) #embed.set_thumbnail('tesco.png') #embed.set_image('https://cdn.shopify.com/s/files/1/0382/7695/6292/files/logo_360x.png?v=1587069640') #embed.set_footer( ts=True,) embed.post()
def on_status(self, status): print("New tweet from monitored handle:") print(status.text) ifvoid = 0 #finds "RT" in first 2 characters of a tweet (retweet) if((str(status.text[:2]).find("RT")) != -1): print("This is a retweet or someone abusing the negative filter, we'll ignore this!") ifvoid = 1 #finds "https://" anywhere in the tweet" elif((str(status.text).find("https://")) != -1 and ifvoid == 0): print("This tweet is an image or link!") #sends tweet contents to discord embed = Webhook(url) embed.set_desc("@everyone - NEW LINK/IMAGE FROM " + handle + ":") embed.add_field(name="Tweet Contents", value=str(status.text)) embed.set_footer(text="Twitter Monitor by @__ized on twitter",ts=True) embed.post() print("Tweet Sent to Discord!") #finds and sends expanded url to discord foundurls = re.findall(r'(https?://\S+)', str(status.text)) urlnumber = len(foundurls) print("Number of URLs in tweet: " + urlnumber) currenturl = 1 while currenturl <= urlnumber: uri = urlexpander.unshorten(foundurls[currenturl - 1]) embed = Webhook(url) embed.set_desc("Expanded URL:") embed.add_field(name="-->", value=uri) embed.set_footer(text="Twitter Monitor by @__ized on twitter",ts=True) embed.post() currenturl = currenturl + 1 print("Expanded URL " + uri + " Sent To Discord!") #finds "@" in the first character of a tweet (reply) elif((str(status.text[:1]).find("@")) == 0 and ifvoid == 0): print("This is likely a reply or other tweet, will not send") else: print("This is a regualr tweet, will send!") embed = Webhook(url) embed.set_desc("New tweet from " + handle + ":") embed.add_field(name="Tweet Contents", value=str(status.text)) embed.set_footer(text="Twitter Monitor by @__ized on twitter",ts=True) embed.post()
def send_embed(alert_type, product): ''' (str, str, list, str, str, str) -> None Sends a discord alert based on info provided. ''' # Set webhook url = https://discordapp.com/api/webhooks/555053278308859927/D1AsxzUajXuA3fchYuXwq_ib2OHW3S-UpNNYyYanoW7W2Eo9rBb-evVneSeRyPX_SOy7 # Create embed to send to webhook embed = Webhook(url, color=123123) # Set author info embed.set_author(name='NERYS', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg') # Set product details if(alert_type == "RESTOCK"): embed.set_desc("RESTOCK: " + product.title) elif(alert_type == "NEW"): embed.set_desc("NEW: " + product.title) embed.add_field(name="Product", value=product.title) embed.add_field(name="Link", value=product.link) embed.add_field(name="Stock", value=str(product.stock)) # Set product image embed.set_thumbnail(product.image) embed.set_image(product.image) # Set footer embed.set_footer(text='NERYS by @snivynGOD', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg', ts=True) # Send Discord alert embed.post()
def send_embed(product): ''' (Product) -> None Sends a discord alert based on info provided. ''' url = 'https://discordapp.com/api/webhooks/555053278308859927/D1AsxzUajXuA3fchYuXwq_ib2OHW3S-UpNNYyYanoW7W2Eo9rBb-evVneSeRyPX_SOy7' embed = Webhook(url, color=123123) embed.set_author( name='NERYS', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg') embed.set_desc("Found product based on keyword " + product.keyword) embed.add_field(name="Link", value=product.link) embed.set_footer( text='NERYS by @snivynGOD', icon='https://static.zerochan.net/Daenerys.Targaryen.full.2190849.jpg', ts=True) embed.post()
def send_embed(alert_type, product): url = discord_webhook embed = Webhook(url, color=123123) embed.set_author(name='ARB', icon='https://sun9-74.userapi.com/impf/x8e2VAfW-ao86OPcoUeSKpB7sup-dlIC3bT-2g/I3Vwk9su7D8.jpg?size=564x532&quality=96&sign=423037df9ddf5c5400c93844710086c3&type=album') if(alert_type == "RESTOCK"): embed.set_desc("RESTOCK: " + product.title) elif(alert_type == "NEW"): embed.set_desc("NEW: " + product.title) embed.add_field(name="Product", value=product.title) embed.add_field(name="Link", value=product.link) embed.add_field(name="Stock", value=str(product.stock)) # Set product image embed.set_thumbnail(product.image) embed.set_image(product.image) # Set footer embed.set_footer(text='ARB by @JaqueFresco', icon='https://sun9-11.userapi.com/impf/DagUwT61wIcd0BeLtPOI3UFtf2nV2ZK9Gh-8NQ/ehNPfNbLWGA.jpg?size=754x750&quality=96&sign=ce4bfc72ef8fdcfbbf3c11dbd8589382&type=album', ts=True) # Send Discord alert embed.post()
res = requests.get('https://forum.gamer.com.tw/B.php?bsn=60599&subbsn=10') BotWebHook = 'Your webhook url' res.encoding = 'utf-8' soup = BeautifulSoup(res.text, "html.parser") PostLists = soup.find('table', {'class': 'b-list'}) Posts = PostLists.find_all('tr', {'class': 'b-list__row'}) Title = Posts[0].find('td', {'class': 'b-list__main'}).text WebsiteUrl = 'https://forum.gamer.com.tw/' + Posts[0].find( 'td', { 'class': 'b-list__main' }).a['href'] sha1 = hashlib.sha1((Title).encode("utf-8")).hexdigest() checkvalue = check('18c8', sha1) embed = Webhook(BotWebHook, color=123123) embed.set_author(name='Steamти┤тЊѕтДєуЅ╣тЁЇУ▓╗жЂіТѕ▓ТЃЁта▒', icon='') embed.set_desc(Title + WebsiteUrl) #embed.add_field(name='Test Field',value='Value of the field \U0001f62e') #embed.add_field(name='Another Field',value='1234 Ъўё') #embed.set_thumbnail('https://i.imgur.com/rdm3W9t.png') embed.set_image( 'https://pbs.twimg.com/profile_images/663739181231792128/58-mQCZh_400x400.png' ) #embed.set_footer(text='уЎ╝ТќЄТЎѓжќЊ '+post_time,icon='',ts=True) if (checkvalue == 1): print("No") elif (checkvalue == 0): embed.post()