def discord_webhook(product_item): hook = Webhook(url="") """ Sends a Discord webhook notification to the specified webhook URL :param product_item: An array of the product's details :return: None """ embed = Embed(color=int(16711816)) if product_item == 'initial': embed.description = 'NBA Top Shot Monitor // INITIALISED // Twitter: @LNDNHYPE :smile:' else: embed.set_author('NBA Top Shot Monitor') embed.set_title(title=f'{product_item[1]}') # Item Name embed.add_field(name='Price:', value=product_item[2], inline=True) embed.add_field(name='Stock Count:', value=product_item[4], inline=True) embed.add_field(name='Remaining:', value=product_item[3], inline=True) embed.add_field(name='Pre Order:', value=product_item[5], inline=False) #embed.set_thumbnail(product_item[4]) embed.set_footer( text= f'Developer Twitter: @LNDNHYPE • {datetime.now().strftime("%Y-%m-%d %H:%M")}', icon_url='https://i.imgur.com/jjOXloc.png') try: hook.send(embed=embed) except requests.exceptions.HTTPError as err: print(err) logging.error(msg=err) else: print("Payload delivered successfully") logging.info("Payload delivered successfully")
async def server_stop(app, loop): """Sends a message to the webhook channel when server stops.""" em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
async def init(app, loop): """Sends a message to the webhook channel when server starts.""" app.session = aiohttp.ClientSession(loop=loop) # to make web requests app.webhook = Webhook.Async(webhook_url, session=app.session) em = Embed(color=0x2ecc71) em.set_author('[INFO] Starting Worker') em.description = 'Host: {}'.format(socket.gethostname()) await app.webhook.send(embed=em)
def post_to_discord(product_pid): f****d = False while not f****d: proxy_picked = proxyhandler.proxy() try: productz, _product_styles, _item_url, url, price = products.get_info(product_pid, proxy_picked) f****d = True eve_qt = 'http://remote.eve-backend.net/api/quick_task?link=' + url price = int(price) / 100 parsed_uri = urlparse(url) result = '{uri.netloc}'.format(uri=parsed_uri) with open('webhook.json') as json_file: json_dump = json.load(json_file) for site_name in json_dump: if site_name in result: webhookz = json_dump[site_name]['webhook'] embed = Embed() for webhook in webhookz: for x in productz: product = x.split('@') name = product[0] image = product[1] stock = product[2] client = Webhook(webhook) embed.description(f'[{name}]({url})') embed.add_field(name='Stock',value=stock) embed.add_field(name='Price',value=price) embed.add_field(name='Quick Tasks', value=f'[EVE]({eve_qt})',inline='false') embed.set_thumbnail(image) embed.set_footer(text=f'Supreme Monitor by @TaquitoSlayer') client.send('Posting...', embeds=[embed]) # simplejson.errors.JSONDecodeError except Exception as e: logging.info(f'{url.upper()} SOMETHING WRONG - SLEEPING FOR {delay} SECONDS') logging.info(f'{e}') time.sleep(float(delay)) pass
async def on_error(request, exception): resp = {'success': False, 'error': str(exception)} try: raise (exception) except: excstr = traceback.format_exc() print(excstr) if len(excstr) > 1000: excstr = excstr[:1000] em = Embed(color=Color.red) em.set_author('[ERROR] Exception occured on server') em.description = f'```py\n{excstr}```' em.set_footer(f'Host: {socket.gethostname()}') app.add_task(app.webhook.send(embed=em)) return response.json(resp, status=500)
def webhooker(): content = 'wwwweeeeeee' url = 'dummy.com' webhook_url = os.environ['WEBHOOK'] client = Webhook(webhook_url) logging.info('Image posted! on facebook') FacebookWebhook = Embed() FacebookWebhook.color = 0xC0FFEE # colors should be a hexadecimal value FacebookWebhook.description = 'The bot has new content!\n Is this another sentient post or not?' FacebookWebhook.add_field(name=content, value=str(datetime.datetime.utcnow() + datetime.timedelta(hours=+8)), inline=False) FacebookWebhook.set_image(url) FacebookWebhook.set_footer( text=f'\u00A9 AbanteBot6969 | Series of 2019 ', ) client.send('\u200b', embed=FacebookWebhook) logging.info( '===================== SUCCESS!! , Exiting....=====================')
async def _announcements(request): auth_token = request.headers.get('Authorization', None) channel_id = request.json.get("channel_id") msg = request.json['msg'] webhook = request.json.get('webhook',False) await app.ctx.db.execute_job(f"INSERT INTO announcements(msg) VALUES ('{msg}')") if auth_token == app.ctx.sse_token: try: await request.app.sse_send(msg, channel_id=channel_id) except KeyError: abort(HTTPStatus.NOT_FOUND, "channel not found") await app.ctx.db.execute_job("UPDATE seen SET seen='f'") if webhook: em = Embed(color=0x2ecc71, timestamp='now') em.set_author('Announcement', icon_url='https://cdn.discordapp.com/attachments/782105673928146984/984431266516598844/unknown.png') em.description = msg em.set_footer(text='https://opho.physoly.tech/announcements', icon_url='https://cdn.discordapp.com/attachments/782105673928146984/984431266516598844/unknown.png') await app.ctx.webhook.send(embed=em) return json({"status":"ok"}) return response.json({'error' : 'unauthorized'}, status=401)
def stripe_endpoint(): body = request.data.decode('utf-8') signature_header = request.headers.get('Stripe-Signature', None) try: event = stripe.Webhook.construct_event( body, signature_header, STRIPE_WEBHOOK_SECRET ) if event['type'] in EVENTS: embed = Embed( title=' '.join(event['type'].split('.')).title(), color=0x646EDE, timestamp='now' ) embed.set_footer(text=event['data']['object']['id'], icon_url='https://i.imgur.com/FpXfweu.png') if 'subscription' in event['type']: subscription = event['data']['object'] embed.description = '> [**Customer**](https://dashboard.stripe.com/customers/{})\n'\ '> [**Subscription**](https://dashboard.stripe.com/subscriptions/{})'.format( subscription['customer'], subscription['id'] ) if subscription.get('canceled_at'): embed.add_field(name='**Status**', value=subscription['status'].title()) embed.add_field( name='**Canceled**', value=datetime.fromtimestamp(subscription['canceled_at']).strftime('%B %-d, %Y') ) embed.add_field( name='**Ends**', value=datetime.fromtimestamp(subscription['cancel_at']).strftime('%B %-d, %Y') ) else: embed.add_field(name='**Status**', value=subscription['status'].title()) embed.add_field( name='**Starts**', value=datetime.fromtimestamp(subscription['current_period_start']).strftime('%B %-d, %Y') ) embed.add_field( name='**Renews**', value=datetime.fromtimestamp(subscription['current_period_end']).strftime('%B %-d, %Y') ) elif 'customer' in event['type']: customer = event['data']['object'] embed.description = '> [**Customer**](https://dashboard.stripe.com/customers/{})'.format(customer['id']) if customer.get('description'): embed.description = customer['description'] if customer.get('name'): embed.add_field(name='**Name**', value=customer['name']) if customer.get('email'): embed.add_field(name='**Email**', value=customer['email']) if customer.get('address'): embed.add_field(name='**Address**', value=customer['address'], inline=False) elif 'invoice' in event['type']: invoice = event['data']['object'] embed.description = '> [**Customer**](https://dashboard.stripe.com/customers/{})\n'\ '> [**Invoice**](https://dashboard.stripe.com/invoices/{})'.format( invoice['customer'], invoice['id'] ) embed.add_field(name='**Status**', value=invoice['status'].title()) embed.add_field( name='**Amount Paid**', value='{} {}'.format(float(invoice['amount_paid']) / 100, invoice['currency'].upper()) ) embed.add_field(name='**Attempts**', value=str(invoice['attempt_count'])) embed.add_field(name='**Customer Email**', value=invoice['customer_email']) DISCORD_WEBHOOK.send(embed=embed, username='******') return '', 200 except stripe.error.SignatureVerificationError: return 'Bad Request', 400 except: return 'Internal Server Error', 500
from dhooks import Embed, Webhook ### webhook_url = "<INSERT WEBHOOK URL HERE>" ### client = Webhook(webhook_url) # NOTE: Following code has a solid rundown of all methods # within the embed class. em1 = Embed() em1.color = 0x00FF00 # colors should be a hexadecimal value em1.description = """This description supports [named links](https://discord.com) as well. ``` \n yes, even code blocks``` """ em1.timestamp = "2018-04-30T05:34:26-07:00" em1.set_author(name='Author Goes Here', icon_url='https://i.imgur.com/rdm3W9t.png', url='https://discord.com/') em1.set_title(title='title ~~(did you know you can have markdown here too?)~~', url='https://discord.com/') em1.add_field(name="Field 1 :smiley:",
def fbpost(): logging.debug('Starting Facebook Thread') with open("headlines.txt", encoding='utf-8-sig') as f: text = f.read() text_model = markovify.NewlineText(text) content = text_model.make_short_sentence(100, tries=100) r = content.split(' ') remove = [ 'ng', 'nang', 'sa', 'at', 'ang', 'na', 'kay', 'ni', 'mga', 'nila', 'nina' ] for i in remove: for f in r: if i == f: r.remove(f) else: pass f = random.choices(r, k=1) print(f) safe = [] for i in f: safe.append(re.sub('[\W_]', '', str(i))) safe string = '+'.join(safe) html = urlopen(f'https://www.philstar.com/search/{string}/age=720') #html = urlopen('https://www.philstar.com/search/maine%20saka') print(html) soup = BeautifulSoup(html, 'html.parser') #imgs = soup.find_all('a',class_='img-holder') img = [] for i in soup.find_all('div', attrs={'class': 'tiles_image'}): print(i.find('img')) img.append(i.find('img')) img print(img) urls = [] for i in img: print(i['src']) urls.append(i['src']) urls imgurls = random.choice(urls) urllib.request.urlretrieve(imgurls, "preface.png") size = width, height = 712, 483 image = Image.new('RGB', size, 'white') preface = Image.open("preface.png") article = Image.open('article.png') rez = preface.resize((712, 373), Image.LANCZOS) image.paste(rez, (0, 0)) image.paste(article, (0, 0), article) draw = ImageDraw.Draw(image) ar = ImageFont.truetype('arialbd.ttf', 27) lines = textwrap.wrap(content, width=50) y_text = 405 for line in lines: width, height = ar.getsize(line) draw.text((21, y_text), line, font=ar, fill='#000000') y_text += height #draw.text((21, 405),content, font=ar, fill='#000000') image.save('outfile.png', 'PNG') del image del draw fb_token = os.environ['TOKEN_PAINTMIN'] graph = facebook.GraphAPI(access_token=fb_token, version="3.1") post = graph.put_photo(image=open('outfile.png', "rb"), message=content) graph.put_object( parent_object=post['post_id'], connection_name='comments', message= 'Please hit the mf like button.\n Disclaimer: This is computer generated content. Any headlines that con-incide to real events are purely coincidental.' ) webhook_url = os.environ['WEBHOOK'] client = Webhook(webhook_url) FacebookWebhook = Embed() FacebookWebhook.color = 0xC0FFEE # colors should be a hexadecimal value FacebookWebhook.description = 'The bot has new content!\n Is this another sentient post or not?' FacebookWebhook.add_field(name=content, value=str(datetime.datetime.utcnow() + datetime.timedelta(hours=+8)), inline=False) FacebookWebhook.set_image(imgurls) FacebookWebhook.set_footer( text=f'\u00A9 AbanteBot6969 | Series of 2019 ', ) client.send('\u200b', embed=FacebookWebhook) logging.debug( '=====================SUCCESS POSTING FB, Exiting....=====================' )
def restock_monitor(url): # logging.info(f'SUPREME RESTOCK MONITOR - {url}') """ Problem with this restock function is that the first item gets stored, then the other does, but the first item gets compared with ALL items first before moving onto next one""" f****d = False while not f****d: proxy_picked = proxyhandler.proxy() try: productz, _product_styles, _item_url, full_url, price = products.get_info(url, proxy_picked) eve_qt = 'http://remote.eve-backend.net/api/quick_task?link=' + full_url price = int(price) / 100 print('step 1') for x in productz: product = x.split('@') name = product[0] image = product[1] stock_initial = f'{name}@{int(product[2])}' print('step 2') while True: productz_n, _product_styles, item_url, _url, price = products.get_info(url, proxy_picked) f****d = True for y in productz_n: print('step 3') product_n = y.split('@') stock_new = f'{name}@{int(product_n[2])}' # diff = list(set(stock_new) - set(stock_initial)) print(stock_initial) print(stock_new) diff = list(set(stock_new) - set(stock_initial)) print(diff) time.sleep(1) if bool(diff) == True: stock = ''.join(diff) if int(stock) > 0: print('found stock difference') print(item_url) parsed_uri = urlparse(item_url) result = '{uri.netloc}'.format(uri=parsed_uri) print(result) with open('webhook.json') as json_file: print('opened json') json_dump = json.load(json_file) for site_name in json_dump: print(site_name) if site_name in result: print('supreme found') webhookz = json_dump[site_name]['webhook'] embed = Embed() for webhook in webhookz: logging.info(f'NEW STOCK UPDATE FOUND') client = Webhook(webhook) embed.description = f'[{name}]({item_url})' embed.add_field(name='Stock',value=stock) embed.add_field(name='Price',value=price) embed.add_field(name='Quick Tasks', value=f'[EVE]({eve_qt})',inline='false') embed.set_thumbnail(image) embed.set_footer(text=f'Supreme Restock Monitor by @TaquitoSlayer') client.send(embeds=[embed]) stock_initial = stock_new print('stock changed') elif bool(diff) == False: logging.info(f'no changes found - {url}') pass else: logging.info('Nothing new found') pass except Exception as e: logging.info(f'{url.upper()} SOMETHING WRONG - SLEEPING FOR {delay} SECONDS') raise Exception time.sleep(float(delay)) pass
def restock_monitor(url): # logging.info(f'SUPREME RESTOCK MONITOR - {url}') """ Problem with this restock function is that the first item gets stored, then the other does, but the first item gets compared with ALL items first before moving onto next one Pretty sure I fixed it... Let's see how it works """ f****d = False while not f****d: proxy_picked = proxyhandler.proxy() try: productz, _product_styles, _item_url, full_url, price = products.get_info(url, proxy_picked) eve_qt = 'http://remote.eve-backend.net/api/quick_task?link=' + full_url price = int(price) / 100 price = str(price) print(price) # product = x.split('@') # name = product[0] # image = product[1] # stock_initial = f'{name}@{int(product[2])}' while True: productz_n, _product_styles, item_url, _url, _price = products.get_info(url, proxy_picked) f****d = True # print('step 3') # product_n = y.split('@') # stock_new = f'{name}@{int(product_n[2])}' # diff = list(set(stock_new) - set(stock_initial)) diff = list(set(productz_n) - set(productz)) print(diff) time.sleep(1) if bool(diff) == True: diff = diff[0] product = diff.split('@') name = product[0] image = product[1] stock = f'{int(product[2])}' if int(stock) > 0: print('found stock difference') print(item_url) parsed_uri = urlparse(item_url) result = '{uri.netloc}'.format(uri=parsed_uri) print(result) with open('webhook.json') as json_file: json_dump = json.load(json_file) for site_name in json_dump: print(site_name) if site_name in result: webhookz = json_dump[site_name]['webhook'] embed = Embed() for webhook in webhookz: logging.info(f'NEW STOCK UPDATE FOUND') client = Webhook(webhook) item_url = item_url.replace('.json', '') embed.description = f'[{name}]({item_url})' embed.add_field(name='Stock',value=stock) embed.add_field(name='Price',value=price) embed.add_field(name='Quick Tasks', value=f'[EVE]({eve_qt})',inline='false') embed.set_thumbnail(image) embed.set_footer(text=f'Supreme Restock Monitor by @TaquitoSlayer') client.send(embeds=[embed]) embed.fields.clear() productz = productz_n print('stock changed') elif bool(diff) == False: logging.info(f'no changes found - {url}') pass else: logging.info('Nothing new found') pass except Exception as e: logging.info(f'{url.upper()} - ERROR FOUND!') logging.info(f'error: {e}')