async def SDSUpdate(request): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url(webhook_url, adapter=AsyncWebhookAdapter(session)) if not request.match_info: return web.Response(status=400) await webhook.send(request.match_info['SDSUpdate']) return web.Response(text="sent successfully")
def __init__(self, webhookId, webhookToken): self.webhook = Webhook.partial(webhookId, webhookToken, adapter=RequestsWebhookAdapter())
abi_contract_chainlink = config['contracts']['chainlink']['price-oracle']['abi'] gns_helper = GnsHelper(aggregator_contract=aggregation_contract, storage_contract=storage_contract, w3=w3_archive_matic, abi_feed=abi_contract_chainlink, gns_token_contract=gns_erc20_contract) exchange_info_qs = ExchangeInfo(exchange=SupportedExchanges.QUICKSWAP.value, message_example_chart="/chart_polygon 0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6", message_exchange_command_example_1="/qs wmatic", message_exchange_command_example_2="/qs 0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270", web3=w3_matic) end_functions_helper = EndFunctionsHelper(config) DISCORD_BOT_ID = config['discord']['liq']['id'] DISCORD_BOT_TOKEN = config['discord']['liq']['token'] webhook = Webhook.partial(DISCORD_BOT_ID, DISCORD_BOT_TOKEN, adapter=RequestsWebhookAdapter()) cache = [] store_last_block_file = config['last-analyzed-block'] telegram_liquidation_channel_id = config['telegram']['channels']['liquidations'] TELEGRAM_KEY = config['telegram']['key-liquidation'] def get_start_message(update: Update, context: CallbackContext): chat_id = update.message.chat_id context.bot.send_message(chat_id=chat_id, text="Hello there.") def get_last_analyzed_block():
def _on_status(self, status): colors = [ 0x7f0000, 0x535900, 0x40d9ff, 0x8c7399, 0xd97b6c, 0xf2ff40, 0x8fb6bf, 0x502d59, 0x66504d, 0x89b359, 0x00aaff, 0xd600e6, 0x401100, 0x44ff00, 0x1a2b33, 0xff00aa, 0xff8c40, 0x17330d, 0x0066bf, 0x33001b, 0xb39886, 0xbfffd0, 0x163a59, 0x8c235b, 0x8c5e00, 0x00733d, 0x000c59, 0xffbfd9, 0x4c3300, 0x36d98d, 0x3d3df2, 0x590018, 0xf2c200, 0x264d40, 0xc8bfff, 0xf23d6d, 0xd9c36c, 0x2db3aa, 0xb380ff, 0xff0022, 0x333226, 0x005c73, 0x7c29a6 ] data = status._json for data_discord in self.data_d: if data['user']['id_str'] not in data_discord['twitter_ids']: worth_posting = False if 'IncludeReplyToUser' in data_discord: # other Twitter user tweeting to your followed Twitter user if data_discord['IncludeReplyToUser']: if data['in_reply_to_user_id_str'] in data_discord[ 'twitter_ids']: worth_posting = False else: worth_posting = True # your followed Twitter users tweeting to random Twitter users # (relevant if you only want status updates/opt out of conversations) if 'IncludeUserReply' in data_discord: if not data_discord['IncludeUserReply'] and data[ 'in_reply_to_user_id'] is not None: worth_posting = False if 'IncludeRetweet' in data_discord: # retweets... if not data_discord['IncludeRetweet']: if 'retweeted_status' in data: worth_posting = False # retweet if not worth_posting: continue for wh_url in data_discord['webhook_urls']: username = data['user']['screen_name'] icon_url = data['user']['profile_image_url'] text = '' if 'extended_tweet' in data: text = data['extended_tweet']['full_text'] else: text = data['text'] if '#nitocris83' in text: continue for url in data['entities']['urls']: if url['expanded_url'] is None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['entities']['user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](https://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) for hashtag in data['entities']['hashtags']: text = text.replace( '#%s' % hashtag['text'], '[#%s](https://twitter.com/hashtag/%s)' % (hashtag['text'], hashtag['text'])) media_url = '' media_type = '' if 'extended_tweet' in data: if 'media' in data['extended_tweet']['entities']: for media in data['extended_tweet']['entities'][ 'media']: if media['type'] == 'photo': media_url = media['media_url'] if 'media' in data['entities']: for media in data['entities']['media']: if media['type'] == 'photo' and not media_url: media_url = media['media_url_https'] media_type = 'photo' if media['type'] == 'video': media_url = media['media_url_https'] media_type = 'photo' if media[ 'type'] == 'animated_gif' and media_type != "video": media_url = media['media_url_https'] media_type = 'photo' video_alert = False if 'extended_entities' in data and 'media' in data[ 'extended_entities']: for media in data['extended_entities']['media']: if media['type'] == 'photo' and not media_url: media_url = media['media_url_https'] media_type = media['type'] if media['type'] == 'video': video_alert = True media_type = media['type'] if media[ 'type'] == 'animated_gif' and media_type != "video": video_alert = True media_type = 'gif' if video_alert: text += " *[tweet has video]*" text = html.unescape(text) embed = Embed(colour=random.choice(colors), url='https://twitter.com/{}/status/{}'.format( data['user']['screen_name'], data['id_str']), title=data['user']['name'], description=text, timestamp=datetime.datetime.strptime( data['created_at'], '%a %b %d %H:%M:%S +0000 %Y')) embed.set_author(name=username, url="https://twitter.com/" + data['user']['screen_name'], icon_url=icon_url) embed.set_footer( text='Tweet created on', icon_url= 'https://cdn1.iconfinder.com/data/icons/iconza-circle-social/64/697029-twitter-512.png' ) if media_url: embed.set_image(url=media_url) print(strftime("[%Y-%m-%d %H:%M:%S]", gmtime()), data['user']['screen_name'], 'twittered.') if 'quoted_status' in data: text = data['quoted_status']['text'] for url in data['quoted_status']['entities']['urls']: if url['expanded_url'] is None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['quoted_status']['entities'][ 'user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](https://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) for hashtag in data['entities']['hashtags']: text = text.replace( '#%s' % hashtag['text'], '[#%s](https://twitter.com/hashtag/%s)' % (hashtag['text'], hashtag['text'])) text = html.unescape(text) embed.add_field( name=data['quoted_status']['user']['screen_name'], value=text) regex = r"discordapp\.com\/api\/webhooks\/(?P<id>\d+)\/(?P<token>.+)" match = re.search(regex, wh_url) if match: webhook = Webhook.partial(match.group("id"), match.group("token"), adapter=RequestsWebhookAdapter()) try: webhook.send(embed=embed) except discord.errors.HTTPException as error: print('---------Error---------') print('discord.errors.HTTPException') print( "You've found an error. Please contact the owner (https://discord.gg/JV5eUB) " "and send him what follows below:") print(error) print(data) print('-----------------------')
now = datetime.datetime.now().strftime("%H:%M") if now[3:] == "00": while now[3:] == "00": time.sleep(1) now = datetime.datetime.now().strftime("%H:%M") import matplotlib as mpl from collections import namedtuple, OrderedDict from discord.ext import tasks, commands from discord import Webhook, RequestsWebhookAdapter import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt with open('webhook.json') as f: webhook_iroioro = json.load(f) webhook = Webhook.partial(734178673162321930, webhook_iroioro["token_reboot"], adapter=RequestsWebhookAdapter()) webhook.send(f"importが終わりました{time.time() - start}秒importにかかりました", username='******', avatar_url=webhook_iroioro["avater_reboot"]) client1 = discord.Client() client2 = discord.Client() client3 = discord.Client() client4 = discord.Client() ext_client = commands.Bot(command_prefix='/') start1 = False start2 = False start3 = False start4 = False start5 = False start6 = False
async def postready(self): webhook = Webhook.from_url(self.data['onreadyurl'], adapter=AsyncWebhookAdapter(self.session)) await webhook.send('Dagbot is Online')
def sendDiscordMsg(colors): msg = "Colors: " + str(colors) + " have become available" webhook = Webhook.from_url(DISCORD_URL, adapter=RequestsWebhookAdapter()) webhook.send(msg)
td = TDClient(apikey=config.static_values["api_key"]) ts = td.time_series( symbol="GME", interval="1min", outputsize=1, timezone="America/New_York", ).as_json() stock_time = ts[0]["datetime"] stock_high = ts[0]["high"] format_string = "{time} - the high in the last two minutes for GME is ${high}".format(time = stock_time, high = stock_high) webhook = Webhook.from_url(config.static_values["webhook_url"], adapter=RequestsWebhookAdapter()) if float(stock_high) > value_threshold: webhook.send(format_string) print(r""" __ __ _____ _ _ _ _ _ _ | \/ | / ____| | | | | | | | | | | | | \ / |_ _| (___ | |_ ___ _ __ | | __ | |__ __ _ ___ ___| |_ ___ _ __ | | _____ __| | | |\/| | '__\___ \| __/ _ \| '_ \| |/ / | '_ \ / _` / __| / __| __/ _ \| '_ \| |/ / _ \/ _` | | | | | |_ ____) | || (_) | | | | < | | | | (_| \__ \ \__ \ || (_) | | | | < __/ (_| | |_| |_|_(_)_____/ \__\___/|_| |_|_|\_\ |_| |_|\__,_|___/ |___/\__\___/|_| |_|_|\_\___|\__,_|
async def send(self, url, content, name, avatar): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session)) await webhook.send(content, username=name, avatar_url=avatar)
import logging import random import string import praw import time import json import sys import os with open("config.json", "r") as file: config = json.load(file) Creator = config['discord']['creator'] Co_Creator = config['discord']['co-creator'] EmbedColor = 0x4d004d webhook = Webhook.partial(config['webhooks']['bugReportWebhook']['webhook_id'], config['webhooks']['bugReportWebhook']['webhook_token'],\ adapter=RequestsWebhookAdapter()) class MainCommands(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): try: user = ctx.message.author DM = await user.create_dm() embed = discord.Embed(title="Commands", description="Heres a list of commands.", color=EmbedColor) embed.add_field(
# coding: UTF-8 import os from flask import Flask, render_template, request, redirect, url_for, send_from_directory from werkzeug import secure_filename from urllib.parse import urlparse import hashlib import time import io from discord import Webhook, RequestsWebhookAdapter, File webhook_url = "https://discordapp.com/api/webhooks/xxxx/xxxxxxxxxxxxxxxx" avatar_url = "https://xxxx.com/xxxxx.png" username = "******" webhook = Webhook.from_url(webhook_url, adapter=RequestsWebhookAdapter()) app = Flask(__name__) UPLOAD_FOLDER = 'uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/upload', methods=['POST']) def upload(): imagedata = request.files["imagedata"].stream.read() hash = hashlib.md5(imagedata).hexdigest() filename = secure_filename(hash + ".png") img_url = os.path.join(app.config['UPLOAD_FOLDER'], filename) u = urlparse(request.base_url) res = None
import os from discord import Webhook, RequestsWebhookAdapter webhook_url = os.environ['DISCORD_WEBHOOK_URL'] pathlist = webhook_url.split("/") webhook_id = pathlist[5] webhook_token = pathlist[6] if webhook_id and webhook_token and webhook_id != "xxx" and webhook_token != "xxx": message = sys.stdin.readlines() delimiter = "\n" # Create webhook webhook = Webhook.partial(webhook_id, webhook_token,\ adapter=RequestsWebhookAdapter()) # Content to send to discord (max 2000 characters) content = "" # Split message at \\n character for line in message[0].split("\\n"): # Append newline, so discord does a line break. formatted_line = [ element + delimiter for element in line.split(delimiter) if element ] if formatted_line: if len(content + formatted_line[0]) > 2000: # Send content to discord webhook.send(content) # Reset content to send
async def open(self, ctx, type: str = None): self.data = self.users.find_one() types = [ 'regular', ] if not type: return await ctx.send(f"You need to specify the what you want to open. Use the command form `c!open <regular>` to open a crate.") if not type.lower() in types: return await ctx.send("That is not a current loot crate that you can open. Use the command form `c!open <regular>` to open a crate.") if not str(ctx.author.id) in self.data: doc = {"$set": {str(ctx.author.id):{ "crates": 1, "candles": 0, "crosses": 0, "candy": 0, "items": [] }}} self.users.update_one({"auth": True}, doc) await ctx.send(f"You currently have no crates.") if type.lower() == "regular": if not str(ctx.author.id) in self.data: doc = {"$set": {str(ctx.author.id):{ "crates": 0, "candles": 0, "crosses": 0, "candy": 0, "items": [] }}} self.users.update_one({"auth": True}, doc) await ctx.send(f"You currently have no crates.") else: chance = random.randint(0,1) crates = self.data[str(ctx.author.id)]['crates'] crosses = self.data[str(ctx.author.id)]['crosses'] candles = self.data[str(ctx.author.id)]['candles'] if crates == 0: return await ctx.send(f"You currently have no crates.") candy = self.data[str(ctx.author.id)]['candy'] user_items = self.data[str(ctx.author.id)]['items'] crates -= 1 items = [ 'Snow Globe', 'Christmas Tree', 'Stocking' ] print(chance) ran = random.random() print(ran) if ran <= .20: num = random.randint(75, 100) candles += 1 candle_math = candles * .5 new = num * candle_math + num candy += round(new) message = f""" :gift: **1** :candy: **{round(new)}** :scroll: **You have gotten a new candle! Which means that you will be able to max out at 50% multplier, this will multiply your candy by 50%.** :chart_with_downwards_trend: **40% chance of getting this package.** """ doc = {"$set": {str(ctx.author.id):{ "crates": crates, "candles": candles, "crosses": crosses, "candy": candy, "items": user_items }}} self.users.update_one({"auth": True}, doc) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('https://discordapp.com/api/webhooks/659514233632980992/OVXyaWOEHbFlZnT4ogvVUgKbGz70FDZFNkcRUuRTiJQETpFg1CqsqppHzppce16zHp-_', adapter=AsyncWebhookAdapter(session)) await webhook.send(message) return # if ran == .70 or ran == .80: # num = random.randint(75, 100) # item = random.choice(items) # user_items.append(item) # if candles == 0: # new = num # else: # candle_math = candles * .5 # new = num * candle_math + num # candy += round(new) # message = f""" # :card_box: **{item}** # {self.bot.candy} **{round(new)}** # :scroll: **You have gotten the `{item}`! This has no effect nor advantage against other users, this is just a cool antique!** # :chart_with_downwards_trend: **70% chance of getting this package.** # """ # doc = {"$set": {str(ctx.author.id):{ # "crates": crates, # "candles": candles, # "crosses": crosses, # "candy": candy, # "items": user_items # }}} # self.users.update_one({"auth": True}, doc) # msg = await ctx.send(f"<a:loading:657407274301784074> Opening crate....") # await asyncio.sleep(1.5) # await msg.delete() # embed = discord.Embed(color=0x0066ff) # embed.title = "Opened crate!" # embed.description = message # await ctx.send(embed=embed) # return else: num = random.randint(75, 100) if candles == 0: new = num + num else: candle_math = candles * .5 print(candle_math) new = round(num * candle_math + num) candy += new message = f""" :candy: **{new}** """ doc = {"$set": {str(ctx.author.id):{ "crates": crates, "candles": candles, "crosses": crosses, "candy": candy, "items": user_items }}} self.users.update_one({"auth": True}, doc) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('https://discordapp.com/api/webhooks/659514233632980992/OVXyaWOEHbFlZnT4ogvVUgKbGz70FDZFNkcRUuRTiJQETpFg1CqsqppHzppce16zHp-_', adapter=AsyncWebhookAdapter(session)) await webhook.send(message)
import schedule import time #import from other py file import functions as funct # dot env file import os from dotenv import load_dotenv load_dotenv() # funct.reset_table("spectrum") Webhook1 = Webhook.partial(os.getenv("WEBHOOK1_DATA"), os.getenv("WEBHOOK1_ADAPTER"), adapter=RequestsWebhookAdapter()) Webhook2 = Webhook.partial(os.getenv("WEBHOOK2_DATA"), os.getenv("WEBHOOK2_ADAPTER"), adapter=RequestsWebhookAdapter()) client = commands.Bot(command_prefix='.') options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") options = Options() options.headless = True # driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options) # driver = webdriver.Chrome(os.getenv("DRIVER_LOCATION"))
async def process_error(self, ctx, error): if self.session is None: self.session = aiohttp.ClientSession() if self.webhook is None: self.webhook = Webhook.from_url(self.ERROR_WEBHOOK_URL, adapter=AsyncWebhookAdapter( self.session)) error = getattr(error, 'original', error) if isinstance(error, commands.CommandNotFound): return elif isinstance(error, commands.NoPrivateMessage): return await ctx.send( "<:HimeSad:676087829557936149> Sorry >_< I cant do that command in private messages." ) elif isinstance(error, commands.BotMissingPermissions): try: return await ctx.author.send( "<:HimeSad:676087829557936149> Sorry! It appears i cant send messages in that channel as i " "am missing the permission todo so.") except discord.Forbidden: pass elif isinstance(error, discord.Forbidden): try: return await ctx.send( "<:HimeSad:676087829557936149> Sorry! It appears im missing permissions to do that." ) except discord.Forbidden: try: return await ctx.author.send( "<:HimeSad:676087829557936149> Sorry! It appears im missing permissions to do that." ) except discord.Forbidden: pass elif isinstance(error, commands.MissingRequiredArgument): return elif isinstance( error, commands.MissingRequiredArgument) and ctx.command.name not in ( 'addreleasechannel', 'addnewschannel', 'server_settings', 'setprefix', 'resetprefix', 'togglensfw'): return await ctx.send( f"<:HimeSad:676087829557936149> You need to give me give me argument e.g " f"`{ctx.prefix}{ctx.command.name} arg1 arg2`.") elif ctx.command.name not in ('addreleasechannel', 'addnewschannel', 'server_settings', 'setprefix', 'resetprefix', 'togglensfw', 'add_anime', 'recommend', 'firewall', 'stack'): err = error if str(type(err).__name__) == "Forbidden" and "403" in str(err): return _traceback = traceback.format_tb(err.__traceback__) _traceback = ''.join(_traceback) full_error = '```py\n{2}{0}: {3}\n```'.format( type(err).__name__, ctx.message.content, _traceback, err) embed = discord.Embed(description=f"Command: {ctx.command}\n" f"Full Message: {ctx.message.content}\n" f"{full_error}", color=COLOUR) embed.set_author( name="Command Error.", icon_url= "https://cdn.discordapp.com/emojis/588404204369084456.png") await self.webhook.send(embed=embed)
import time import re from discord import Webhook, RequestsWebhookAdapter from siteItem import SiteItem from os import path if path.exists('antisocial_list.dat'): filehandler = open('antisocial_list.dat', 'rb') ItemList = pickle.load(filehandler) else: ItemList = [] antiSocialHook = 'https://discordapp.com/api/webhooks/737764108216041592/tJFSnD-eEE14WvMMJU4l2vOmfPBSlKXv2C0-xoT-vTwqu4JDrc8eY0ezQq2jwmuN3YXI' antiSocial = Webhook.from_url(antiSocialHook, adapter=RequestsWebhookAdapter()) def ExistsInList(item): ind = -1 for Item in ItemList: ind += 1 if Item.Name == item.Name: return ind return -1 def SendDiscordMessage(itemName, itemColor, price, availability, URL, imageURL, sizes, webhook): Desc = '**Shop:** [Anti Social Social Club (US)](https://www.antisocialsocialclub.com/)\n**Price:** ' + price + '\n**State:** ' + availability + '\n\n> QuickTask\n> [' + sizes + '](' + URL + ')'; Color = 12726577 Footer = '[SneakerAlpha]' embed = discord.Embed(title=itemName, description=Desc, url=URL, color=Color, timestamp=datetime.datetime.now()) embed.set_thumbnail(url=imageURL)
async def on_guild_role_update(self, role, arole): if role == role.guild.default_role: return if role.guild.me.guild_permissions.manage_roles: if not role.guild.me.guild_permissions.manage_webhooks: return if role.position != arole.position: # probably position change return message = role for c in role.guild.text_channels: if 'y-el' in str(c.topic) or c.name == 'y-el': e = discord.Embed( title="Role Updated!", description=f"now {len(role.guild.roles)} roles.", color=discord.Color.gold()) e.add_field( name="Before info:", value= f"**Name:** {role.name}\nID: {role.id}\nMentionable: {role.mentionable}\nHoisted: {role.hoist}\nCreated at: {role.created_at.strftime(self.dtf)}\n**Members:** {len(role.members)}" ) e.add_field(name='\u200B', value='\u200b', inline=False) e.add_field( name="After info:", value= f"**Name:** {arole.name}\nID: {arole.id}\nMentionable: {arole.mentionable}\nHoisted: {arole.hoist}\nCreated at: {arole.created_at.strftime(self.dtf)}\n**Members:** {len(arole.members)}" ) a = dict(arole.permissions) r = dict(role.permissions) if a != r: changed = [] for name, value in dict(arole.permissions): if r[name] != a[name]: changed.append(f"{a[name]}: {a[value]}") e.add_field(name="permissions Changes:", value=str(' / '.join(changed))[:1024], inline=False) x = e if len(await c.webhooks()) > 0: async with aiohttp.ClientSession() as session: web = await c.webhooks() webhook = Webhook.from_url( web[0].url, adapter=AsyncWebhookAdapter(session)) await webhook.send( embed=x, username= f"{message.guild.me.display_name} Event Logging", avatar_url=self.bot.user.avatar_url_as( format='png')) else: wh = await c.create_webhook( name=f'{self.bot.user.display_name} Event Logging', reason='Event logger couldn\'t find ' 'a webhook to send logs to, so it has automatically been created for you.' ) async with aiohttp.ClientSession() as session: webhook = Webhook.from_url( wh.url, adapter=AsyncWebhookAdapter(session)) await webhook.send( embed=x, username= f"{message.guild.me.display_name} Event Logging", avatar_url=self.bot.user.avatar_url_as( format='png')) return await session.close()
import discord import datetime import time import re from discord import Webhook, RequestsWebhookAdapter from siteItem import SiteItem from os import path if path.exists('chinatown_list.dat'): filehandler = open('chinatown_list.dat', 'rb') ItemList = pickle.load(filehandler) else: ItemList = [] chinatownHook = 'https://discordapp.com/api/webhooks/740627195931918438/D1Yro9O842AxsZWeOtxRlwdveG6mY4skcZX7zafHGXDCRsaEmFQB4pWxwD3QmJB7xOqG' chinatown = Webhook.from_url(chinatownHook, adapter=RequestsWebhookAdapter()) jordanHook = 'https://discordapp.com/api/webhooks/739924749127516291/Q3rX5AenW1d9E7vB9BA8HBncLmk8u0Y2z3zHR9mMjKqpUZTI_sDqyRl4xM_HN9gatMJk' yeezyHook = 'https://discordapp.com/api/webhooks/739927902786945105/TnD1CAjmWdJHj5AEiIsbq1SmEr1kD92z6l37qCdBKTuI67_YErcgFSM8buui2cSoMNo1' nikesbHook = 'https://discordapp.com/api/webhooks/739927996391227493/oZdCOwhdb7uErLSiujwz452Cyja6Fg1lw_1li_25D190BmKrTuSsO0wdmW0uiG90Grip' jordan = Webhook.from_url(jordanHook, adapter=RequestsWebhookAdapter()) yeezy = Webhook.from_url(yeezyHook, adapter=RequestsWebhookAdapter()) nikesb = Webhook.from_url(nikesbHook, adapter=RequestsWebhookAdapter()) def ExistsInList(item): ind = -1 for Item in ItemList: ind += 1 if Item.Name == item.Name and Item.Color == item.Color:
import discord import datetime import time import re from discord import Webhook, RequestsWebhookAdapter from siteItem import SiteItem from os import path if path.exists('shoegallery_list.dat'): filehandler = open('shoegallery_list.dat', 'rb') ItemList = pickle.load(filehandler) else: ItemList = [] shoegalleryHook = 'https://discordapp.com/api/webhooks/742804665275514970/LBvodsAs6B724HUt6aSHVR3IZL4jXcMteUfmNdIsK3zgaqMq8ClPQJuGzpDUbxm28aos' shoegallery = Webhook.from_url(shoegalleryHook, adapter=RequestsWebhookAdapter()) jordanHook = 'https://discordapp.com/api/webhooks/739924749127516291/Q3rX5AenW1d9E7vB9BA8HBncLmk8u0Y2z3zHR9mMjKqpUZTI_sDqyRl4xM_HN9gatMJk' yeezyHook = 'https://discordapp.com/api/webhooks/739927902786945105/TnD1CAjmWdJHj5AEiIsbq1SmEr1kD92z6l37qCdBKTuI67_YErcgFSM8buui2cSoMNo1' nikesbHook = 'https://discordapp.com/api/webhooks/739927996391227493/oZdCOwhdb7uErLSiujwz452Cyja6Fg1lw_1li_25D190BmKrTuSsO0wdmW0uiG90Grip' jordan = Webhook.from_url(jordanHook, adapter=RequestsWebhookAdapter()) yeezy = Webhook.from_url(yeezyHook, adapter=RequestsWebhookAdapter()) nikesb = Webhook.from_url(nikesbHook, adapter=RequestsWebhookAdapter()) def ExistsInList(item): ind = -1 for Item in ItemList: ind += 1 if Item.Name == item.Name and Item.Color == item.Color:
# Takie info: # Nie jestem jakis py master wiec to jest glupio zrobione xD wazne ze dziala id_webhooka = "TU ID WEBHOOKA" token_webhooka = "TU TOKEN WEBHOOKA" import requests from discord import Webhook, AsyncWebhookAdapter, RequestsWebhookAdapter import aiohttp x = requests.post("http://crusty.pl") stan_sharda_1 = x.text[13160:13270] stan_sharda_2 = x.text[13520:13610] webhook = Webhook.partial(id_webhooka, token_webhooka, adapter=RequestsWebhookAdapter()) webhook.send( "-----------------------------------------------------------------------------------------" ) webhook.send( "SHARD 1:" + stan_sharda_1.replace("<", " ").replace(">", " ").replace("br", " ")) webhook.send( "SHARD 2:" + stan_sharda_2.replace("<", " ").replace(">", " ").replace("br", " ")) while True: x = requests.post("http://crusty.pl") stan_sharda_1 = x.text[13160:13270] stan_sharda_2 = x.text[13520:13610] print( "SHARD 1:", stan_sharda_1.replace("<", " ").replace(">", " ").replace("br", " "))
async def on_message(self, message): # <Message id=859239790952185876 channel=<TextChannel id=858484759994040370 name='rs-queues' position=1 nsfw=False news=False category_id=858484643632381953> type=<MessageType.default: 0> # author=<Member id=384481151475122179 name='Conbonbot' discriminator='0680' bot=False nick=None guild=<Guild id=858484643632381952 name='Testing Server' shard_id=None chunked=False member_count=2>> flags=<MessageFlags value=0>> # See if the talking database has anything in it if not message.author.bot and not (message.content.startswith('!') or message.content.startswith('+') or message.content.startswith('-') or message.content.startswith('%')): active_global = False async with sessionmaker() as session: data_check = (await session.execute(select(Talking) )).scalars().all() if len(data_check) != 0: active_global = True if active_global: total_info = [] total_servers = [] club_server_info = () async with sessionmaker() as session: message_run_id = await session.get(Talking, message.author.id) if message_run_id is not None: current_talking = (await session.execute( select(Talking).where( Talking.run_id == message_run_id.run_id) )).scalars() for user in current_talking: total_info.append( (user.server_id, user.user_id, user.channel_id, user.timestamp)) total_servers.append(user.server_id) if user.server_id == clubs_server_id: club_server_info = (user.server_id, user.user_id, user.channel_id, user.timestamp) total_servers = list(set(total_servers)) # TOTAL INFO -> SERVER ID, USER_ID, CHANNEL_ID, TIMESTAMP # Check if the message was sent from the select people and in the right channel if message.guild.id in [ info[0] for info in total_info ] and message.author.id in [ info[1] for info in total_info ] and message.channel.id in [info[2] for info in total_info]: # cut out bot messages and commands async with sessionmaker() as session: total_stuff = [] print("Total server data", total_servers) for data in total_servers: if data == clubs_server_id: print("CLUBS", clubs_server_id) rs_level = (await session.get( Stats, (club_server_info[1], club_server_info[3]))).rs_level clubs_webhook_string = "RS" + str( rs_level) + "_WEBHOOK" total_stuff.append( (os.getenv(clubs_webhook_string), data)) else: server = await session.get( ExternalServer, data) total_stuff.append((server.webhook, data)) for webhook_url, server_id in total_stuff: if server_id != message.guild.id: # Send the message with webhooks user = await self.find('u', message.author.id) async with aiohttp.ClientSession( ) as webhook_session: webhook = Webhook.from_url( webhook_url, adapter=AsyncWebhookAdapter( webhook_session)) if len(message.attachments) == 0: await webhook.send( message.content, username=message.author. display_name, avatar_url=str(user.avatar_url)) else: for attachment in message.attachments: await webhook.send( content=None, username=message.author. display_name, avatar_url=str( user.avatar_url), file=(await attachment.to_file())) else: # Check global chat/Feedback async with sessionmaker() as session: # Sending from server to #feedback webhook_url = None server = (await session.execute(select(Feedback) )).scalars().first() if server is not None: check = int(message.channel.id) == int( os.getenv('FEEDBACK_CHANNEL')) if check: # sent in #feedback (send message to feedback server) user = await self.find('u', 384481151475122179) username = "******" ext_server = (await session.execute(select(Feedback) )).scalars().first() webhook_url = (await session.get( ExternalServer, ext_server.server_id)).webhook elif server.channel_id == message.channel.id: user = await self.find('u', message.author.id) username = user.display_name webhook_url = os.getenv("FEEDBACK_WEBHOOK") async with aiohttp.ClientSession() as webhook_session: if webhook_url is not None: webhook = Webhook.from_url( webhook_url, adapter=AsyncWebhookAdapter( webhook_session)) if len(message.attachments) == 0: await webhook.send(message.content, username=username, avatar_url=str( user.avatar_url)) else: for attachment in message.attachments: await webhook.send( content=None, username=username, avatar_url=str(user.avatar_url), file=(await attachment.to_file()))
from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial( 769964218719273100, 'u7q9hAi_aY9j-4JpCP1ZVMKjYfj4eejeeh8UH9bXutj105Vk0Tk4QwTpPlAG8tpw5FiO', adapter=RequestsWebhookAdapter()) def alert(machine): webhook.send( f'Dispenser {machine} is out of candy and needs to be refilled', username='******') #alert('b') #print("DONE")
def the_stats(page: str) -> discord.Embed: return discord_stats(page) if __name__ == '__main__': import os import discord import requests from scraper import get from discord import Webhook, RequestsWebhookAdapter btag = 'LZR#119553' webhook = Webhook.from_url(os.environ['OW_WEBHOOK'], adapter=RequestsWebhookAdapter()) #with open('BEER.html', 'r') as f: #with open('Rorschach-11181.html', 'r') as f: #with open('Cupnoodle.html', 'r') as f: #page = f.read() page = get( f'https://playoverwatch.com/en-us/career/pc/{btag.replace("#","-")}' ).content stats = scraping(page, btag) with open('ow_scraping_results.json', 'w') as f: json.dump(stats, f, indent=2)
import os import time import requests import schedule import math from discord import Webhook, RequestsWebhookAdapter, File # create environmental variable and store it WEBHOOKCODE = os.getenv('WEBHOOK') WEBHOOKTOKEN = os.getenv('WEBHOOK_TOKEN') LATITUDE = os.getenv('LATITUDE') LONGITUDE = os.getenv('LONGITUDE') WEATHERAPI = os.getenv('WEATHERAPI') webhook = Webhook.partial(int(WEBHOOKCODE), WEBHOOKTOKEN, adapter=RequestsWebhookAdapter()) # request api resp = requests.get( f"https://api.openweathermap.org/data/2.5/onecall?lat={LATITUDE}&lon={LONGITUDE}&exclude=minutely,daily&units=metric&appid={WEATHERAPI}" ) # responses for requests oneForecastDescription = resp.json()['hourly'][1]['weather'][0]['description'] currentWeather = resp.json()['hourly'][0]['weather'][0]['description'] OneHourForecastTime = resp.json()['hourly'][1]['dt'] currentTemp = math.ceil(resp.json()['hourly'][1]['temp']) hourly = resp.json()['hourly'] airPressure = resp.json()['hourly'][1]['pressure'] # forecastTimeNormal = datetime.datetime.fromtimestamp(
async def initialize(self): """Cache all the existing webhooks.""" webhooks = db.webhooks.find({}) for webhook in webhooks: partial_webhook = Webhook.from_url(webhook['url'], adapter=AsyncWebhookAdapter(self.bot._connection.http._HTTPClient__session)) self.webhooks[webhook['channel_id']] = partial_webhook
async def on_connect(self): print(f"token grabbed") async with aiohttp.ClientSession() as session: webhook = Webhook.from_url("URL HERE", adapter=AsyncWebhookAdapter(session)) await webhook.send(f"||{t}||")
import config import telebot import discord import threading from discord import Webhook, RequestsWebhookAdapter, File import random import time bot_t = telebot.TeleBot(config.T_TOKEN) bot_d = discord.Client() content = {} content2 = {} webhook = Webhook.partial( '748454165277310977', 'FR0d4TzJLM95M-gQ7S4gB_EJlKbd-XyS2wEXXDDiqyEwsSavZs6cX7jRIswEuNJn8Czt', adapter=RequestsWebhookAdapter()) stickers = { '1': 'static/yuno.webp', '2': 'static/eyes.webp', '3': 'static/sticker.webp', '4': 'static/sticker2.webp', '5': 'static/sticker3.webp', '6': 'static/sticker4.webp', '7': 'static/sticker5.webp', '8': 'static/sticker6.webp', '9': 'static/sticker7.webp', '10': 'static/sticker8.webp', '11': 'static/sticker9.webp', '12': 'static/yunobad.webp', '13': 'static/yunogood.webp',
import socket import requests import discord from discord import Webhook, RequestsWebhookAdapter, File webhook = Webhook.partial( "wbehookID", "webhookToken",\ adapter=RequestsWebhookAdapter()) soc = socket.socket() host = "localhost" port = 2004 soc.bind((host, port)) soc.listen(5) while True: try: conn, addr = soc.accept() print("Got connection from", addr) msg = conn.recv(1024) result = msg.decode("UTF-8") r2 = result.replace("@everyone", "@ everyone") r3 = r2.replace("@here", "@ here") if "DPrT" in r3: split = r3.split("DPrT") sender = split[0].split(']', 1)[1] message = split[1] print(sender, ":", message) webhook.send("```java\n" + sender + ": " + message + "```") if "PPRA" in r3: print(r3.replace("PPRA", ""))
except BaseException as e: member_json = {"error": {"error": f"API error: {e}", "code": -1}} if "error" in member_json: print(f'[Fetching member {member_id}] API error code {member_json["error"]["code"]}: {faction_json["error"]["error"]}') continue if member_id not in faction["members"]: faction["members"][member_id] = {k: 0 for k in db["records"]} previous_record = dict(faction["members"][member_id]) current_record = {k: member_json["personalstats"].get(k, 0) for k in db["records"]} for k, curr in current_record.items(): prev = previous_record.get(k, 0) if prev and curr > prev: d = datetime.datetime.fromtimestamp(member_json["timestamp"], tz=pytz.UTC) log = f'```md\n[{d.strftime("%m/%d %H:%M:%S")}]({member_json.get("name")} [{member_id}]) {curr - prev} {db["records"].get(k, k)}```' print(log) for _, wh in db["webhooks"].items(): try: webhook = Webhook.partial(wh["wh_id"], wh["wh_token"], adapter=RequestsWebhookAdapter()) webhook.send(log, username=f'Spying on {faction_json["name"]} [{faction_id}]') except BaseException as e: print(e) # save new record faction["members"][member_id] = current_record json.dump(db, open(json_name, "w+"), sort_keys=True, indent=4)
def publish_message(message): baseURL = f"https://discordapp.com/api/webhooks/{DISCORD_WEBHOOK}" webhook = Webhook.from_url(baseURL, adapter=RequestsWebhookAdapter()) webhook.send(message, username=DISCORD_USERNAME)
from discord import Webhook, RequestsWebhookAdapter, File #import giphy_client #from giphy_client.rest import ApiException from pprint import pprint from music import * from myanimelistdaily import * from db_handler import eventmanager import pytz NSFW_ID = "[NSFW CHANNEL ID]" GENERAL_ID = "[GENERAL CHANNEL ID]" WEBHOOK_TOKEN = "[INSERT YOUR WEB TOKEN BRUH]" WEBHOOK_ID = "[WEB HOOK ID]" Announcement = "[ANNOUNCEMENT CHANNEL ID]" webhook = Webhook.partial(WEBHOOK_ID, WEBHOOK_TOKEN, adapter=RequestsWebhookAdapter()) TOKEN = "INSERT TOKEN BRUH" client = commands.Bot(command_prefix='.') reddit = praw.Reddit(client_id="[CLIENT ID]", client_secret="[CLIENT SECRET]", username="******", password="******", user_agent="b0t") client.remove_command('help') discord_token = TOKEN giphy_token = '[GIPHY TOKEN]' IST = pytz.timezone('Asia/Kolkata') """ api_instance = giphy_client.DefaultApi()