def test_archive_url_format(): pb = Pastebin() archive_list = pb.get_archive() for link in archive_list: assert re.match(r'https://pastebin\.com/[a-zA-Z0-9]{8}', link).group() == link
async def errorWrite(string, exception): logFile = open(os.path.dirname(os.path.realpath(__file__)) + "/logs/errors.log", 'a+', encoding="utf-8") logFile.write( "----------------------------------------------------------------------------------------------------------------------------------------------------------------\n" ) logFile.write("[" + datetime.datetime.now().strftime("%m-%d-%Y %H:%M:%S") + "] " + str(string) + "\n" + traceback.format_exc()) me = await client.fetch_user(157662210481586176) eMessage = "```" + str(string) + "\n" + traceback.format_exc() + "```" if (len(eMessage) >= 2000): pb = Pastebin(pbKey) pb.authenticate(pbUser, pbPass) url = pb.create_paste(eMessage, api_paste_private=1, api_paste_name="ERROR: " + type(exception).__name__) await me.send("ERROR: " + url) else: await me.send(eMessage) logFile.close()
def __init__(self, config): self.config = config # Create IRC bot connection server = 'irc.chat.twitch.tv' port = 6667 print('Connecting to ' + server + ' on port ' + str(port) + '...') irc.bot.SingleServerIRCBot.__init__(self, [(server, port, 'oauth:'+config.twitch_oauth)], config.twitch_username, config.twitch_username) # try to connect to livesplit server self._init_livesplit_server() # read livesplit config to get active comparisons self.active = {'Personal Best': True} with config.livesplit_config.open() as livesplit_config_file: livesplit_config_root = BeautifulSoup(livesplit_config_file, 'html.parser') comparison_settings = livesplit_config_root.find('comparisongeneratorstates') for comparison in comparison_settings.find_all(True): is_active = eval(comparison.string) if comparison.string in ['True', 'False'] else False self.active[comparison['name']] = is_active # init spotify client scope = " ".join([ 'user-read-currently-playing', 'user-read-recently-played', ]) self.spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, open_browser=False)) # this will output an authorization URI to stdout and prompt for the redirect URI, # if not already authorized self.spotify.current_user_playing_track() # init pastebin client self.pastebin = Pastebin(config.pastebin_dev_key) self.pastebin.authenticate(config.pastebin_username, config.pastebin_password)
def test_archive_url_format(): pb = Pastebin() archive_list = pb.get_archive() print(archive_list) for id in archive_list: print(id) reg = re.match(r"[a-zA-Z0-9]{8}", id) assert reg.group() == id
def upload_paste_thread(text): global config pb = Pastebin(api_dev_key=environ.get('PASTEBIN_API_KEY')) pasteurl = pb.create_paste(text, api_paste_expire_date=config['SHARE']['PasteExpire'], api_paste_name=config['SHARE']['PasteTitle']) if "Bad API request" in pasteurl: pasteurl = "Upload error" return pasteurl
def exportSnippets(self, message: core.BotMessage) -> None: """Exports the snippets to Pastebin Arguments: message {Message} -- the Message object that invoked the command """ kind = 'fact' snippetList = self.factList if "topic" in message.arguments[0]: kind = 'topic' snippetList = self.topicList elif "quote" in message.arguments[0]: kind = 'quote' snippetList = self.quoteList if message.room: room = message.room elif len(message.arguments) > 1: room = message.connection.getRoom(message.arguments[1]) else: return message.respond("You must specify a room.") if not message.sender.can("addfact", room): return message.respond("Permission denied.") if room.id not in snippetList.keys() or len(snippetList[room.id]) == 0: return message.respond( f"There are no {kind}s for the room {room.id}.") pasteData = "\n".join(snippetList[room.id]) return message.respond( str( Pastebin(config.pastebinAPIKey).create_paste( pasteData, # the data 1, # unlisted paste f"{kind.title()}s for room {room.id}" # title )))
updateTime = datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f') PIC = '' # person in control current_datetime = '' filedate = '' clock = datetime.now() load_dotenv() # load the secret from the .env file TOKEN = os.getenv('DISCORD_TOKEN') # variable token stores the secret PASTEAPI = os.getenv('PASTEBIN_TOKEN') PASTEUSERKEY = os.getenv('PASTEBIN_USERKEY') client = discord.Client() # variable to store client info pastebin = Pastebin(PASTEAPI) def RIVMdata(locatie, tijd): global filedate # used for adding to .txt database global current_datetime if locatie == 'database': with open('database.txt', 'r') as database: RIVM = database.read() pasteurl = pastebin.create_paste(RIVM, api_paste_private=0, api_paste_name=None, api_paste_expire_date='10M', api_paste_format='text') # print all info to the text file return pasteurl if locatie == 'gemeentelijst': with open('database.txt', 'r') as csv_file: # open the file as a csv
import pytz import tweepy from datetime import date from discord_webhook import DiscordWebhook, DiscordEmbed from pbwrap import Pastebin # Set script up to work with Twitter auth = tweepy.OAuthHandler("YOUR_API_KEY", "YOUR_API_SECRET_KEY") auth.set_access_token("YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET") #Create API object api = tweepy.API(auth) #PasteBin setup API_DEV_KEY = 'YOUR_PASTEBIN_API_DEV_KEY' pb = Pastebin(API_DEV_KEY) pb.authenticate("PASTEBIN_USERNAME", "PASTEBIN_PASSWORD") # Get today's date local_tz = pytz.timezone('YOUR/TIMEZONE/HERE') today = date.today() def utc_to_local(utc_dt): local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt) def aslocaltimestr(utc_dt): return utc_to_local(utc_dt).strftime('%m/%d/%Y, %I:%M:%S %p')
print("Bot Strting") load_dotenv() if development == True: import configparser print("development mode") config = configparser.ConfigParser() config.read('config.ini') bot = commands.Bot(command_prefix='*') TOKEN = config['discord']['BOT_TOKEN'] GUILD = config['discord']['GUILD'] CHANNEL = config['discord']['CHANNEL'] database = Database(config['discord']['database']) im = pyimgur.Imgur(config['discord']['imgur_token']) pb = Pastebin(config['discord']['pastebin_key']) else: import environ env = environ.Env(DEBUG=(bool, False)) bot = commands.Bot(command_prefix='#') TOKEN = env('BOT_TOKEN_ACTIVITY') GUILD = env('GUILD') CHANNEL = env('CHANNEL') database = Database(env('DB_URL')) im = pyimgur.Imgur(env('IMGUR_TOKEN')) pb = Pastebin(env('PASTEBIN_KEY')) @bot.event async def on_ready(): await bot.change_presence(activity=discord.Game(name="Making Drinks"))
def fetch_pb(self): pb = Pastebin('') pb.authenticate(os.environ['DEFAULTUSER'],os.environ['PBINKEY']) return pb
class AbsentHelper(irc.bot.SingleServerIRCBot): KNOWN_COMPARISONS = { 'pb': 'Personal Best', 'best': 'Best Segments', 'bestsplits': 'Best Split Times', 'average': 'Average Segments', 'median': 'Median Segments', 'worst': 'Worst Segments', 'balanced': 'Balanced PB', 'latest': 'Latest Run', 'none': 'None' } MAX_RECV = 4096 def __init__(self, config): self.config = config # Create IRC bot connection server = 'irc.chat.twitch.tv' port = 6667 print('Connecting to ' + server + ' on port ' + str(port) + '...') irc.bot.SingleServerIRCBot.__init__(self, [(server, port, 'oauth:'+config.twitch_oauth)], config.twitch_username, config.twitch_username) # try to connect to livesplit server self._init_livesplit_server() # read livesplit config to get active comparisons self.active = {'Personal Best': True} with config.livesplit_config.open() as livesplit_config_file: livesplit_config_root = BeautifulSoup(livesplit_config_file, 'html.parser') comparison_settings = livesplit_config_root.find('comparisongeneratorstates') for comparison in comparison_settings.find_all(True): is_active = eval(comparison.string) if comparison.string in ['True', 'False'] else False self.active[comparison['name']] = is_active # init spotify client scope = " ".join([ 'user-read-currently-playing', 'user-read-recently-played', ]) self.spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, open_browser=False)) # this will output an authorization URI to stdout and prompt for the redirect URI, # if not already authorized self.spotify.current_user_playing_track() # init pastebin client self.pastebin = Pastebin(config.pastebin_dev_key) self.pastebin.authenticate(config.pastebin_username, config.pastebin_password) def _init_livesplit_server(self): self.livesplit_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.livesplit_server.connect(("localhost", 16834)) except ConnectionRefusedError: self.livesplit_server = None def on_welcome(self, c, e): print('Joining ' + self.config.twitch_channel.strip('#')) c.join(self.config.twitch_channel) def on_pubmsg(self, c, e): parts = e.arguments[0].strip().split(' ', 1) if parts[0][:1] == '!': print(f'got command: {e.arguments[0]}') cmd = parts[0][1:] args = parts[1:] self.command_dispatch(cmd, args) def command_dispatch(self, cmd, args): c = self.connection if cmd == 'splits': if len(args) != 1: c.privmsg(self.config.twitch_channel, 'usage: !splits <comparison>') return self.splits_info(args[0]) elif cmd == 'spotify': if len(args) != 1: c.privmsg(self.config.twitch_channel, 'usage: !spotify <command>') return self.spotify_info(args[0]) elif cmd == 'thoughts': self.latest_pastebin() else: print(f'unrecognized command: {cmd}') def splits_info(self, shorthand): """Queries a local livesplit server for the final time for the given comparison and posts the time in chat. """ c = self.connection comparison = TwitchBot.KNOWN_COMPARISONS.get(shorthand) if not comparison: c.privmsg(self.config.twitch_channel, f'"{shorthand}" is not a shorthand for any known comparison.') elif comparison == 'None': c.privmsg(self.config.twitch_channel, 'why') elif not self.active[comparison]: c.privmsg(self.config.twitch_channel, f'The "{comparison}" comparison is not currently active.') elif not self.livesplit_server: self._init_livesplit_server() if not self.livesplit_server: c.privmsg(self.config.twitch_channel, 'LiveSplit Server isn\'t running at the moment.') else: self._try_get_time(comparison) else: self._try_get_time(comparison) def _try_get_time(self, comparison): c = self.connection time = self._get_final_time(comparison) if not time: self._init_livesplit_server() if not self.livesplit_server: c.privmsg(self.config.twitch_channel, 'LiveSplit Server isn\'t running at the moment.') return time = self._get_final_time(comparison) c.privmsg(self.config.twitch_channel, f'Final time for comparison "{comparison}" is {time}.') def _get_final_time(self, comparison): command = bytes(f'getfinaltime {comparison}\r\n', 'ascii') self.livesplit_server.send(command) return self.livesplit_server.recv(AbsentHelper.MAX_RECV).decode().strip() def spotify_info(self, command): c = self.connection if command == 'current': track_data = self.spotify.current_user_playing_track() if not track_data: c.privmsg(self.config.twitch_channel, 'No currently playing track.') else: track = track_data['item'] c.privmsg(self.config.twitch_channel, self._track_info_message(track)) elif command == 'previous': track_data = self.spotify.current_user_recently_played(limit=1) if 'items' not in track_data or not track_data['items']: c.privmsg(self.config.twitch_channel, 'No recently played tracks.') else: track = track_data['items'][0]['track'] c.privmsg(self.config.twitch_channel, self._track_info_message(track)) def _track_info_message(self, track): track_artists = ', '.join([artist['name'] for artist in track['artists']]) track_name = track['name'] return f'{track_artists} - {track_name}' def latest_pastebin(self): c = self.connection pastes = self.pastebin.get_user_pastes(api_results_limit=1) if not pastes: c.privmsg(self.config.twitch_channel, 'No thoughts.') return paste_title = pastes[0].title paste_date = datetime.fromtimestamp(int(pastes[0].date)) paste_url = pastes[0].url message = f'{paste_title} ({paste_date:%Y-%m-%d}) --- {paste_url}' c.privmsg(self.config.twitch_channel, message)