diff --git a/stampy/env.py b/stampy/env.py index a3fd6e8..fa960dc 100644 --- a/stampy/env.py +++ b/stampy/env.py @@ -46,10 +46,9 @@ def run_migrations_offline(): """ - # if a database path was provided, override the one in alembic.ini - database = context.get_x_argument(as_dictionary=True).get('database') if database: - url = "sqlite:///%s" % database + = context.get_x_argument(as_dictionary=True).get('database'): + url = f"sqlite:///{database}" else: url = config.get_main_option("sqlalchemy.url") @@ -71,10 +70,9 @@ def run_migrations_online(): # get the alembic section of the config file ini_section = config.get_section(config.config_ini_section) - # if a database path was provided, override the one in alembic.ini - database = context.get_x_argument(as_dictionary=True).get('database') if database: - ini_section['sqlalchemy.url'] = "sqlite:///%s" % database + = context.get_x_argument(as_dictionary=True).get('database'): + ini_section['sqlalchemy.url'] = f"sqlite:///{database}" else: ini_section = config.get_section(config.config_ini_section) diff --git a/stampy/plugin/admin.py b/stampy/plugin/admin.py index 2c7c280..1c84a55 100644 --- a/stampy/plugin/admin.py +++ b/stampy/plugin/admin.py @@ -21,11 +21,10 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/admin"] - return triggers + return ["^/admin"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -33,7 +32,7 @@ def run(message): # do not edit this line """ text = stampy.stampy.getmsgdetail(message)["text"] if text and stampy.stampy.is_owner_or_admin(message): - if text.split()[0].lower()[0:6] == "/admin": + if text.split()[0].lower()[:6] == "/admin": admincommands(message) return @@ -89,8 +88,8 @@ def admincommands(message): changenmastertoken(message=message) elif word == "slave": try: - token = texto.split(' ')[3] if token: + = texto.split(' ')[3]: chanlinkslave(message=message, token=token) except: pass @@ -120,8 +119,8 @@ def changenmastertoken(message): if not stampy.plugin.config.config(key='link-master', default=False, gid=chat_id): charset = string.letters + string.digits size = 20 - token = ''.join((random.choice(charset)) for x in range(size)) - generatedtoken = "%s:%s" % (chat_id, token) + token = ''.join((random.choice(charset)) for _ in range(size)) + generatedtoken = f"{chat_id}:{token}" stampy.plugin.config.setconfig(key='link-master', gid=chat_id, value=generatedtoken) logger.debug(msg=_L("Generated token %s for channel %s") % (token, chat_id)) @@ -205,21 +204,24 @@ def chanunlink(message): chat_id = msgdetail["chat_id"] message_id = msgdetail["message_id"] - masterid = stampy.plugin.config.config(key='link', default=False, gid=chat_id) - if masterid: - # Delete link from slave + = stampy.plugin.config.config( + key='link', default=False, gid=chat_id + ): + # Delete link from slave stampy.plugin.config.deleteconfig(key='link', gid=chat_id) # Notify master channel of slave linked - text = _("Channel *%s* with name *%s* has been unlinked as *SLAVE*") % (chat_id, msgdetail['chat_name']) + text = _("Channel *%s* with name *%s* has been unlinked as *SLAVE*") % ( + chat_id, msgdetail['chat_name']) stampy.stampy.sendmessage(chat_id=masterid, text=text, disable_web_page_preview=True, parse_mode="Markdown") # Notify slave of master linked - text = _("This channel has been unliked as *SLAVE* from *MASTER* channel *%s*") % masterid + text = _( + "This channel has been unliked as *SLAVE* from *MASTER* channel *%s*") % masterid text = text + _("\n\nChannel has also been enabled as running in " "isolated mode, use ```/gconfig delete isolated``` to " "revert back to global karma") @@ -242,14 +244,16 @@ def chanshowslave(message): chat_id = msgdetail["chat_id"] message_id = msgdetail["message_id"] - masterid = stampy.plugin.config.config(key='link', default=False, gid=chat_id) - if masterid: - # We've a master channel, report it - text = _("This channel %s is slave of channel %s") % (chat_id, masterid) + = stampy.plugin.config.config( + key='link', default=False, gid=chat_id + ): + # We've a master channel, report it + text = _("This channel %s is slave of channel %s") % ( + chat_id, masterid) else: # We nee to check database to see if we've any slave - sql = "SELECT id from config where key='link' and value='%s'" % chat_id + sql = f"SELECT id from config where key='link' and value='{chat_id}'" cur = stampy.stampy.dbsql(sql=sql) text = _("Defined slaves:\n") diff --git a/stampy/plugin/alias.py b/stampy/plugin/alias.py index d5c1b2c..e178218 100644 --- a/stampy/plugin/alias.py +++ b/stampy/plugin/alias.py @@ -20,11 +20,10 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/alias"] - return triggers + return ["^/alias"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -32,9 +31,9 @@ def run(message): # do not edit this line """ logger = logging.getLogger(__name__) logger.debug(msg=_L("Processing plugin: Code: %s") % __file__) - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:6] == "/alias": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:6] == "/alias": aliascommands(message) return @@ -125,8 +124,8 @@ def deletealias(word, gid=0): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM alias WHERE key='%s' AND gid='%s';" % (word, gid) - logger.debug(msg="rmalias: %s for group %s" % (word, gid)) + sql = f"DELETE FROM alias WHERE key='{word}' AND gid='{gid}';" + logger.debug(msg=f"rmalias: {word} for group {gid}") stampy.stampy.dbsql(sql) return @@ -157,7 +156,7 @@ def listalias(word=False, gid=0): text = _("%s has an alias %s") % (word, value) else: - sql = "select key,value from alias WHERE gid='%s' ORDER BY key ASC;" % gid + sql = f"select key,value from alias WHERE gid='{gid}' ORDER BY key ASC;" cur = stampy.stampy.dbsql(sql) text = _("Defined aliases:\n") table = from_db_cursor(cur) @@ -177,18 +176,18 @@ def createalias(word, value, gid=0): logger = logging.getLogger(__name__) if getalias(value, gid=gid) == word or word.lower() == value.lower(): - logger.error(msg=_L("createalias: circular reference %s=%s for gid %s") % (word, value, gid)) - else: - if not getalias(word, gid) or getalias(word, gid) == word: - # Removing duplicates on karma DB and add - # the previous values - old = stampy.plugin.karma.getkarma(word=word, gid=gid) - stampy.plugin.karma.updatekarma(word=word, change=-old, gid=gid) - stampy.plugin.karma.updatekarma(word=value, change=old, gid=gid) - sql = "INSERT INTO alias(key, value, gid) VALUES('%s','%s', '%s');" % (word, value, gid) - logger.debug(msg="createalias: %s=%s for gid %s" % (word, value, gid)) - stampy.stampy.dbsql(sql) - return + logger.error(msg=_L("createalias: circular reference %s=%s for gid %s") % ( + word, value, gid)) + elif not getalias(word, gid) or getalias(word, gid) == word: + # Removing duplicates on karma DB and add + # the previous values + old = stampy.plugin.karma.getkarma(word=word, gid=gid) + stampy.plugin.karma.updatekarma(word=word, change=-old, gid=gid) + stampy.plugin.karma.updatekarma(word=value, change=old, gid=gid) + sql = f"INSERT INTO alias(key, value, gid) VALUES('{word}','{value}', '{gid}');" + logger.debug(msg=f"createalias: {word}={value} for gid {gid}") + stampy.stampy.dbsql(sql) + return return False @@ -205,7 +204,7 @@ def getalias(word, gid=0): sql = "SELECT key,value FROM alias WHERE key='%s' AND gid='%s';" % string cur = stampy.stampy.dbsql(sql) value = cur.fetchone() - logger.debug(msg="getalias: %s for gid %s" % (word, gid)) + logger.debug(msg=f"getalias: {word} for gid {gid}") try: # Get value from SQL query @@ -218,6 +217,4 @@ def getalias(word, gid=0): # We can define recursive aliases, so this will return the ultimate one if value: return getalias(word=value, gid=gid) - if word: - return word.lower() - return False + return word.lower() if word else False diff --git a/stampy/plugin/autokarma.py b/stampy/plugin/autokarma.py index 86c4c55..26fa6d8 100644 --- a/stampy/plugin/autokarma.py +++ b/stampy/plugin/autokarma.py @@ -28,16 +28,16 @@ def init(): return triggers -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ code = None - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:6] == "/autok": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:6] == "/autok": code = True autokcommands(message) autokarmawords(message) @@ -135,15 +135,11 @@ def getautok(key, gid=0): """ logger = logging.getLogger(__name__) - sql = "SELECT key,value FROM autokarma WHERE key='%s' AND gid='%s';" % (key, gid) + sql = f"SELECT key,value FROM autokarma WHERE key='{key}' AND gid='{gid}';" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[1]) - - logger.debug(msg="getautok: %s - %s for gid %s" % (key, value, gid)) + value = [row[1] for row in data] + logger.debug(msg=f"getautok: {key} - {value} for gid {gid}") return value @@ -158,15 +154,11 @@ def getautokeywords(gid=0): if gid is False: sql = "SELECT distinct key FROM autokarma;" else: - sql = "SELECT distinct key FROM autokarma WHERE gid='%s';" % gid + sql = f"SELECT distinct key FROM autokarma WHERE gid='{gid}';" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - - logger.debug(msg="getautokeywords: %s for gid %s" % (value, gid)) + value = [row[0] for row in data] + logger.debug(msg=f"getautokeywords: {value} for gid {gid}") return value @@ -184,8 +176,8 @@ def createautok(word, value, gid=0): if value in getautok(word): logger.error(msg=_L("createautok: autok pair %s - %s for gid %s already exists") % (word, value, gid)) else: - sql = "INSERT INTO autokarma(key, value, gid) VALUES('%s','%s', '%s');" % (word, value, gid) - logger.debug(msg="createautok: %s=%s for gid %s" % (word, value, gid)) + sql = f"INSERT INTO autokarma(key, value, gid) VALUES('{word}','{value}', '{gid}');" + logger.debug(msg=f"createautok: {word}={value} for gid {gid}") stampy.stampy.dbsql(sql) return True return False @@ -201,8 +193,8 @@ def deleteautok(key, value, gid=0): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM autokarma WHERE key='%s' and value='%s' and gid='%s';" % (key, value, gid) - logger.debug(msg="rmautok: %s=%s for gid %s" % (key, value, gid)) + sql = f"DELETE FROM autokarma WHERE key='{key}' and value='{value}' and gid='{gid}';" + logger.debug(msg=f"rmautok: {key}={value} for gid {gid}") stampy.stampy.dbsql(sql) return True @@ -261,9 +253,7 @@ def autokarmawords(message): for autok in keywords: if autok in text_to_process: # If trigger word is there, add the triggered action - for word in getautok(key=autok, gid=gid): - wordadd.append(word + "++") - + wordadd.extend(f"{word}++" for word in getautok(key=autok, gid=gid)) if wordadd: # Reduce text in message to just the words we encountered to optimize msgdetail["text"] = " ".join(wordadd) diff --git a/stampy/plugin/base.py b/stampy/plugin/base.py index d5fd61d..0a6ec5f 100644 --- a/stampy/plugin/base.py +++ b/stampy/plugin/base.py @@ -17,11 +17,10 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/quit"] - return triggers + return ["^/quit"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -29,7 +28,7 @@ def run(message): # do not edit this line """ text = stampy.stampy.getmsgdetail(message)["text"] if text and stampy.stampy.is_owner_or_admin(message): - if text.split()[0].lower()[0:6] == "/quit": + if text.split()[0].lower()[:6] == "/quit": basecommands(message) return diff --git a/stampy/plugin/chuck.py b/stampy/plugin/chuck.py index c49a12d..08d118d 100644 --- a/stampy/plugin/chuck.py +++ b/stampy/plugin/chuck.py @@ -20,31 +20,31 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/cn"] - return triggers + return ["^/cn"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: if text.split()[0].lower() == "/cn": cn(message=message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = _("Use `/cn ` to get a random Chuck Norris quote based on word\n\n") - return commandtext + return _( + "Use `/cn ` to get a random Chuck Norris quote based on word\n\n" + ) def cn(message): @@ -63,7 +63,7 @@ def cn(message): message_id = msgdetail["message_id"] who_un = msgdetail["who_un"] - logger.debug(msg=_L("Command: %s by %s" % (texto, who_un))) + logger.debug(msg=_L(f"Command: {texto} by {who_un}")) # We might be have been given no command, just stock try: @@ -74,7 +74,7 @@ def cn(message): if not command: url = "https://api.chucknorris.io/jokes/random" else: - url = "https://api.chucknorris.io/jokes/search?query=%s" % command + url = f"https://api.chucknorris.io/jokes/search?query={command}" text = "``` " # we might get more than one result @@ -90,10 +90,7 @@ def cn(message): totalelem = len(result['result']) except: totalelem = 0 - if totalelem > 1: - elem = random.randint(0, totalelem - 1) - else: - elem = 0 + elem = random.randint(0, totalelem - 1) if totalelem > 1 else 0 text += result['result'][elem]['value'] else: text += "Chuck Norris didn't said a word about it." diff --git a/stampy/plugin/cleanlink.py b/stampy/plugin/cleanlink.py index b1dfa5b..3d9374a 100644 --- a/stampy/plugin/cleanlink.py +++ b/stampy/plugin/cleanlink.py @@ -20,9 +20,7 @@ def init(): :return: List of triggers for plugin """ - triggers = ["*"] - - return triggers + return ["*"] def cron(): @@ -32,7 +30,7 @@ def cron(): """ -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -81,12 +79,12 @@ def run(message): # do not edit this line newurl = renewurl - newtexto = newtexto + " " + newurl + newtexto = f"{newtexto} {newurl}" else: - newtexto = newtexto + " " + word + newtexto = f"{newtexto} {word}" if delete: - logger.info("Link cleaner for %s in chat %s" % (who_id, chat_id)) + logger.info(f"Link cleaner for {who_id} in chat {chat_id}") stampy.stampy.sendmessage(chat_id=chat_id, text=newtexto, reply_to_message_id=message_id, disable_web_page_preview=False) @@ -97,11 +95,10 @@ def run(message): # do not edit this line return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = "" - return commandtext + return "" diff --git a/stampy/plugin/comic.py b/stampy/plugin/comic.py index 3b06dac..50e6b6d 100644 --- a/stampy/plugin/comic.py +++ b/stampy/plugin/comic.py @@ -36,7 +36,7 @@ def init(): stampy.stampy.cronme(name="comic", interval=30) for comic in getcomics(): - triggers.extend(["/%s" % comic]) + triggers.extend([f"/{comic}"]) return triggers @@ -50,17 +50,16 @@ def cron(): comics() -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - code = None - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: comiccommands(message) - return code + return None def help(message): # do not edit this line @@ -143,11 +142,7 @@ def getcomics(): sql = "SELECT distinct name FROM comic;" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - + value = [row[0] for row in data] logger.debug(msg=_L("getcomics: %s") % value) return value @@ -187,12 +182,11 @@ def comics(message=False, name=False, all=False): date = datetime.datetime.now() - if name: - sql = "SELECT name,type,channelgid,lastchecked,url from comic WHERE " \ - "name='%s';" % name - else: - sql = "SELECT name,type,channelgid,lastchecked,url from comic" - + sql = ( + f"SELECT name,type,channelgid,lastchecked,url from comic WHERE name='{name}';" + if name + else "SELECT name,type,channelgid,lastchecked,url from comic" + ) if message: msgdetail = stampy.stampy.getmsgdetail(message) message_id = msgdetail["message_id"] @@ -205,11 +199,7 @@ def comics(message=False, name=False, all=False): gidstoping = [] for row in cur: (name, tipo, channelgid, lastchecked, url) = row - if message: - chat_id = msgdetail["chat_id"] - else: - chat_id = channelgid - + chat_id = msgdetail["chat_id"] if message else channelgid if all: datelast = datetime.datetime(year=1981, month=1, day=24) else: @@ -269,7 +259,7 @@ def comics(message=False, name=False, all=False): # Update comics with results so they are not shown next time for comic in stampy.stampy.getitems(comicsupdated): # Update date in SQL so it's not invoked again - sql = "UPDATE comic SET lastchecked='%s' where name='%s'" % (datefor, comic) + sql = f"UPDATE comic SET lastchecked='{datefor}' where name='{comic}'" logger.debug(msg=_L("Updating last checked as per %s") % sql) stampy.stampy.dbsql(sql=sql) @@ -326,7 +316,7 @@ def comicfromurl(name, forceurl=False): logger = logging.getLogger(__name__) - sql = "SELECT url, imgxpath, txtxpath from comic WHERE name='%s';" % name + sql = f"SELECT url, imgxpath, txtxpath from comic WHERE name='{name}';" cur = stampy.stampy.dbsql(sql) date = datetime.datetime.now() @@ -346,7 +336,7 @@ def comicfromurl(name, forceurl=False): items = ['year', 'month', 'day'] for item in items: if item in url: - url = url.replace('#%s#' % item, '%02d', 1) + url = url.replace(f'#{item}#', '%02d', 1) if item == 'year': url = url % year elif item == 'month': @@ -366,7 +356,7 @@ def comicfromurl(name, forceurl=False): tree = html.fromstring(page.content) if imgxpath and imgxpath != 'False': try: - imgsrc = tree.xpath('%s' % imgxpath)[0] + imgsrc = tree.xpath(f'{imgxpath}')[0] except: imgsrc = False else: @@ -374,15 +364,15 @@ def comicfromurl(name, forceurl=False): if txtxpath and txtxpath != 'False': try: - imgtxt = tree.xpath('%s' % txtxpath)[0] + imgtxt = tree.xpath(f'{txtxpath}')[0] except: imgtxt = False else: - imgtxt = "%s: %s/%s/%s" % (name, year, month, day) + imgtxt = f"{name}: {year}/{month}/{day}" if imgsrc: - if imgsrc[0:2] == "//": - imgsrc = 'http:' + imgsrc + if imgsrc[:2] == "//": + imgsrc = f'http:{imgsrc}' elif imgsrc[0] == "/": # imgsrc is relative, prepend url diff --git a/stampy/plugin/config.py b/stampy/plugin/config.py index 055135b..251ff2c 100644 --- a/stampy/plugin/config.py +++ b/stampy/plugin/config.py @@ -18,23 +18,22 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/config", "^/gconfig", "^/lconfig"] - return triggers + return ["^/config", "^/gconfig", "^/lconfig"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:7] == "/config": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:7] == "/config": configcommands(message) - elif text.split()[0].lower()[0:8] == "/gconfig": + elif text.split()[0].lower()[:8] == "/gconfig": configcommands(message) - elif text.split()[0].lower()[0:8] == "/lconfig": + elif text.split()[0].lower()[:8] == "/lconfig": configcommands(message) return @@ -171,7 +170,7 @@ def showconfig(key=False, gid=0): if key: # if word is provided, return the config for that key string = (key,) - sql = "SELECT key,value FROM config WHERE key='%s' AND id='%s';" % (string, gid) + sql = f"SELECT key,value FROM config WHERE key='{string}' AND id='{gid}';" cur = stampy.stampy.dbsql(sql) value = cur.fetchone() @@ -185,7 +184,7 @@ def showconfig(key=False, gid=0): text = _("%s has a value of %s for id %s") % (key, value, gid) else: - sql = "select key,value from config WHERE id='%s' ORDER BY key ASC;" % gid + sql = f"select key,value from config WHERE id='{gid}' ORDER BY key ASC;" cur = stampy.stampy.dbsql(sql) text = _("Defined configurations for gid %s:\n") % gid table = from_db_cursor(cur) @@ -203,16 +202,10 @@ def gconfig(key, default=False, gid=0): :return: value in database for that key """ - # Try custom group configuration - value = config(key=key, default=False, gid=gid) if value: + = config(key=key, default=False, gid=gid): return value - else: - # Try general group configuration - value = config(key=key, default=False, gid=0) - if value: - return value - return default + return value if (value: = config(key=key, default=False, gid=0)) else default def config(key, default=False, gid=0): @@ -253,7 +246,7 @@ def setconfig(key, value, gid=0): logger = logging.getLogger(__name__) if config(key=key, gid=gid): deleteconfig(key, gid=gid) - sql = "INSERT INTO config VALUES('%s','%s', '%s');" % (key, value, gid) + sql = f"INSERT INTO config VALUES('{key}','{value}', '{gid}');" logger.debug(msg=_L("setconfig: %s=%s for id %s") % (key, value, gid)) stampy.stampy.dbsql(sql) return @@ -268,7 +261,7 @@ def deleteconfig(key, gid=0): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM config WHERE key='%s' AND id='%s';" % (key, gid) + sql = f"DELETE FROM config WHERE key='{key}' AND id='{gid}';" logger.debug(msg=_L("rmconfig: %s for id %s") % (key, gid)) stampy.stampy.dbsql(sql) return diff --git a/stampy/plugin/espp.py b/stampy/plugin/espp.py index 85dc3b1..6b9d7db 100644 --- a/stampy/plugin/espp.py +++ b/stampy/plugin/espp.py @@ -20,31 +20,29 @@ def init(): :return: List of triggers for plugin """ - triggers = ["^/espp"] - return triggers + return ["^/espp"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:5] == "/espp": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:5] == "/espp": espp(message=message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = _("Use `/espp ` to get estimated ESPP earnings\n\n") - return commandtext + return _("Use `/espp ` to get estimated ESPP earnings\n\n") def espp(message): @@ -82,8 +80,11 @@ def espp(message): rate = 1 text += _("USD/%s rate ") % currency + str(rate) + "\n" - initial = float(stampy.plugin.config.gconfig(key="espp", default=False, gid=chat_id)) if initial: + = float( + stampy.plugin.config.gconfig( + key="espp", default=False, gid=chat_id) + ): text += _("Initial quote: %s USD\n") % initial try: quote = c.get(ticker) @@ -93,11 +94,7 @@ def espp(message): final = initial text += "" - if initial > final: - pricebuy = final - else: - pricebuy = initial - + pricebuy = min(initial, final) reduced = 0.85 * pricebuy text += _("Buy price: %s USD\n") % reduced diff --git a/stampy/plugin/feed.py b/stampy/plugin/feed.py index f9adfb1..e9bc3ec 100644 --- a/stampy/plugin/feed.py +++ b/stampy/plugin/feed.py @@ -29,12 +29,10 @@ def init(): """ botname = stampy.stampy.getme() - triggers = ["^/feed"] - if botname == 'redken_bot': stampy.stampy.cronme(name="feed", interval=5) - return triggers + return ["^/feed"] def cron(): @@ -46,17 +44,16 @@ def cron(): feeds() -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - code = None - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: rsscommands(message) - return code + return None def help(message): # do not edit this line @@ -143,7 +140,7 @@ def rsscommands(message): code = feeddel(name=name, gid=chat_id) except: code = False - if code is not False: + if code: text = _("Removing feed `%s`") % name stampy.stampy.sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, @@ -173,11 +170,7 @@ def getfeeds(): sql = "SELECT name FROM feeds" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - + value = [row[0] for row in data] logger.debug(msg=_L("getfeeds: %s") % value) return value @@ -193,8 +186,8 @@ def listfeeds(gid=False): sql = "select name,lastchecked,url,interval from feeds" if gid: - sql = "%s%s" % (sql, " WHERE gid=%s" % gid) - sql = "%s%s" % (sql, " ORDER BY name ASC;") + sql = f"{sql} WHERE gid={gid}" + sql = f"{sql} ORDER BY name ASC;" cur = stampy.stampy.dbsql(sql) try: @@ -229,15 +222,15 @@ def feeds(message=False, name=False): gid = False if name: - sql = "SELECT name,gid,lastchecked,url,interval,lastitem from feeds WHERE name='%s'" % name + sql = f"SELECT name,gid,lastchecked,url,interval,lastitem from feeds WHERE name='{name}'" if gid: - extra = "and gid='%s';" % gid - sql = "%s %s" % (sql, extra) + extra = f"and gid='{gid}';" + sql = f"{sql} {extra}" else: sql = "SELECT name,gid,lastchecked,url,interval, lastitem from feeds" if gid: - extra = "WHERE gid='%s'" % gid - sql = "%s %s" % (sql, extra) + extra = f"WHERE gid='{gid}'" + sql = f"{sql} {extra}" cur = stampy.stampy.dbsql(sql) gidstoping = [] @@ -254,11 +247,7 @@ def feeds(message=False, name=False): for row in cur: (name, gid, lastchecked, url, interval, lastitem) = row - if message: - chat_id = msgdetail["chat_id"] - else: - chat_id = gid - + chat_id = msgdetail["chat_id"] if message else gid try: # Parse date or if in error, use past datelast = stampy.stampy.utize(dateutil.parser.parse(lastchecked)) @@ -302,7 +291,7 @@ def feeds(message=False, name=False): # Even if we don't have updated items, update the lastchecked # date for interval to work properly - if len(news) == 0: + if not news: dateitem = stampy.stampy.utize(datelastitem) dateitemfor = dateitem.strftime('%Y/%m/%d %H:%M:%S') feedsupdated.append({'name': name, 'gid': gid, 'dateitem': dateitemfor}) @@ -319,18 +308,24 @@ def feeds(message=False, name=False): if name == "RHJobs": description = item['description'] try: - jobid = re.search('\*\*Job ID\*\*(.*)', description).group(1).strip().replace("_", '') - url = "https://global-redhat.icims.com/jobs/%s/job?iis=A+Red+Hat+Employee&iispid=21098" % jobid + jobid = ( + re.search('\*\*Job ID\*\*(.*)', description)[1] + .strip() + .replace("_", '') + ) + url = f"https://global-redhat.icims.com/jobs/{jobid}/job?iis=A+Red+Hat+Employee&iispid=21098" except: url = None if url and 'USA-' in title: - url = url = "https://us-redhat.icims.com/jobs/%s/job?iis=A+Red+Hat+Employee&iispid=21098" % jobid + url = ( + url + ) = f"https://us-redhat.icims.com/jobs/{jobid}/job?iis=A+Red+Hat+Employee&iispid=21098" if url and title: dateitem = stampy.stampy.utize(dateutil.parser.parse(item["published"])) dateitemfor = dateitem.strftime('%Y/%m/%d %H:%M:%S') - itemtext = '*%s* *%s* - [%s](%s)' % (name, dateitem, title, url) + itemtext = f'*{name}* *{dateitem}* - [{title}]({url})' try: code = stampy.stampy.sendmessage(chat_id=chat_id, text=itemtext, reply_to_message_id=message_id, parse_mode='Markdown') except: @@ -344,7 +339,7 @@ def feeds(message=False, name=False): # Update feeds with results so they are not shown next time for feed in stampy.stampy.getitems(feedsupdated): # Update date in SQL so it's not invoked again - sql = "UPDATE feeds SET lastchecked='%s',lastitem='%s' where name='%s' and gid='%s'" % (datefor, feed['dateitem'], feed['name'], feed['gid']) + sql = f"UPDATE feeds SET lastchecked='{datefor}',lastitem='{feed['dateitem']}' where name='{feed['name']}' and gid='{feed['gid']}'" logger.debug(msg=_L("Updating last checked as per %s") % sql) stampy.stampy.dbsql(sql=sql) @@ -364,20 +359,16 @@ def feedadd(name=False, url=False, gid=0, interval=30): """ logger = logging.getLogger(__name__) - if name and url: - date = datetime.datetime.now() - lastchecked = date.strftime('%Y/%m/%d %H:%M:%S') - sql = "INSERT INTO feeds(name, url, gid, lastchecked, interval) VALUES('%s','%s', '%s', '%s', '%s');" % (name, url, gid, lastchecked, interval) - cur = stampy.stampy.dbsql(sql) - logger.debug(msg=_L("feedadd: %s on %s for group %s") % (name, url, gid)) - # Retrieve last id - sql = "select last_insert_rowid();" - cur = stampy.stampy.dbsql(sql) - lastrowid = cur.fetchone()[0] - else: - lastrowid = False + if not name or not url: + return False - return lastrowid + date = datetime.datetime.now() + lastchecked = date.strftime('%Y/%m/%d %H:%M:%S') + sql = f"INSERT INTO feeds(name, url, gid, lastchecked, interval) VALUES('{name}','{url}', '{gid}', '{lastchecked}', '{interval}');" + cur = stampy.stampy.dbsql(sql) + logger.debug(msg=_L("feedadd: %s on %s for group %s") % (name, url, gid)) + cur = stampy.stampy.dbsql("select last_insert_rowid();") + return cur.fetchone()[0] def feeddel(name=False, gid=0): @@ -391,8 +382,8 @@ def feeddel(name=False, gid=0): logger = logging.getLogger(__name__) code = False if name: - sql = "DELETE FROM feeds WHERE name='%s' AND gid='%s';" % (name, gid) - logger.debug(msg="feeddel: %s, group: %s" % (name, gid)) + sql = f"DELETE FROM feeds WHERE name='{name}' AND gid='{gid}';" + logger.debug(msg=f"feeddel: {name}, group: {gid}") stampy.stampy.dbsql(sql) code = True return code diff --git a/stampy/plugin/forward.py b/stampy/plugin/forward.py index 1fd347d..b4ab2f7 100644 --- a/stampy/plugin/forward.py +++ b/stampy/plugin/forward.py @@ -22,11 +22,10 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/forward"] - return triggers + return ["^/forward"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -36,10 +35,9 @@ def run(message): # do not edit this line logger = logging.getLogger(__name__) msgdetail = stampy.stampy.getmsgdetail(message) - text = msgdetail["text"] - if text: - if text.split()[0].lower()[0:8] == "/forward": + = msgdetail["text"]: + if text.split()[0].lower()[:8] == "/forward": logger.debug(msg=_L("Processing forward commands")) forwardcommands(message) return @@ -77,7 +75,7 @@ def doforward(message, target): url = "%s%s/forwardMessage" % (stampy.plugin.config.config(key="url"), stampy.plugin.config.config(key='token')) - forwardmessageurl = "%s?chat_id=%s&from_chat_id=%s&message_id=%s" % (url, target, chat_id, message_id) + forwardmessageurl = f"{url}?chat_id={target}&from_chat_id={chat_id}&message_id={message_id}" code = False attempt = 0 @@ -225,8 +223,8 @@ def deleteforward(source, target): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM forward WHERE source='%s' AND target='%s';" % (source, target) - logger.debug(msg="rmforward: %s -> %s" % (source, target)) + sql = f"DELETE FROM forward WHERE source='{source}' AND target='{target}';" + logger.debug(msg=f"rmforward: {source} -> {target}") stampy.stampy.dbsql(sql) return @@ -242,7 +240,7 @@ def listforward(source=False): if source: # if source is provided, return the forwards for that source string = (source,) - sql = "SELECT source,target FROM forward WHERE source='%s' ORDER by source ASC;" % string + sql = f"SELECT source,target FROM forward WHERE source='{string}' ORDER by source ASC;" cur = stampy.stampy.dbsql(sql) target = cur.fetchone() @@ -277,8 +275,8 @@ def createforward(source, target): if getforward(source) == target: logger.error(msg=_L("createforward: circular reference %s=%s") % (source, target)) else: - sql = "INSERT INTO forward VALUES('%s','%s');" % (source, target) - logger.debug(msg=_L("createforward: %s=%s" % (source, target))) + sql = f"INSERT INTO forward VALUES('{source}','{target}');" + logger.debug(msg=_L(f"createforward: {source}={target}")) stampy.stampy.dbsql(sql) return return False @@ -293,9 +291,9 @@ def getforward(source): logger = logging.getLogger(__name__) string = (source,) - sql = "SELECT target FROM forward WHERE source='%s';" % string + sql = f"SELECT target FROM forward WHERE source='{string}';" cur = stampy.stampy.dbsql(sql) rows = cur.fetchall() for target in rows: - logger.debug(msg=_L("getforward: %s -> %s" % (source, target[0]))) + logger.debug(msg=_L(f"getforward: {source} -> {target[0]}")) yield target[0] diff --git a/stampy/plugin/help.py b/stampy/plugin/help.py index 60f3413..06f8c56 100644 --- a/stampy/plugin/help.py +++ b/stampy/plugin/help.py @@ -18,19 +18,18 @@ def init(): :return: List of triggers for plugin """ - triggers = ["^/help"] - return triggers + return ["^/help"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:5] == "/help": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:5] == "/help": helpcommands(message=message) return @@ -74,13 +73,11 @@ def helpcommands(message): chat_id = msgdetail['who_id'] message_id = False - # Call plugins to process help messages - commandtext = "" - - for i in stampy.stampy.plugs: - if i.__name__.split(".")[-1] != "help": - commandtext += i.help(message=message) - + commandtext = "".join( + i.help(message=message) + for i in stampy.stampy.plugs + if i.__name__.split(".")[-1] != "help" + ) for i in stampy.stampy.plugs: if i.__name__.split(".")[-1] == "help": commandtext += i.help(message=message) diff --git a/stampy/plugin/highlight.py b/stampy/plugin/highlight.py index 9e4050a..f92f9c6 100644 --- a/stampy/plugin/highlight.py +++ b/stampy/plugin/highlight.py @@ -30,16 +30,16 @@ def init(): return triggers -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ code = None - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:8] == "/hilight": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:8] == "/hilight": code = True hilightcommands(message) hilightwords(message) @@ -132,15 +132,11 @@ def gethilight(uid, word): """ logger = logging.getLogger(__name__) - sql = "SELECT word FROM hilight WHERE gid='%s' AND word='%s';" % (uid, word) + sql = f"SELECT word FROM hilight WHERE gid='{uid}' AND word='{word}';" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - - logger.debug(msg="gethilight: %s for uid %s" % (value, uid)) + value = [row[0] for row in data] + logger.debug(msg=f"gethilight: {value} for uid {uid}") return value @@ -155,15 +151,11 @@ def gethilightwords(uid=False): if uid is False: sql = "SELECT distinct word FROM hilight;" else: - sql = "SELECT distinct word FROM hilight WHERE gid='%s';" % uid + sql = f"SELECT distinct word FROM hilight WHERE gid='{uid}';" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - - logger.debug(msg="gethilightwords: %s for uid %s" % (value, uid)) + value = [row[0] for row in data] + logger.debug(msg=f"gethilightwords: {value} for uid {uid}") return value @@ -178,15 +170,11 @@ def gethilightuids(word=False): if word is False: sql = "SELECT distinct gid FROM hilight;" else: - sql = "SELECT distinct gid FROM hilight WHERE word='%s';" % word + sql = f"SELECT distinct gid FROM hilight WHERE word='{word}';" cur = stampy.stampy.dbsql(sql) data = cur.fetchall() - value = [] - for row in data: - # Fill valid values - value.append(row[0]) - - logger.debug(msg="gethilightuids: %s for word %s" % (value, word)) + value = [row[0] for row in data] + logger.debug(msg=f"gethilightuids: {value} for word {word}") return value @@ -201,10 +189,11 @@ def createhilight(word, uid): logger = logging.getLogger(__name__) if gethilight(word=word, uid=uid): - logger.error(msg=_L("createhilight: word %s for uid %s already exists") % (word, uid)) + logger.error( + msg=_L("createhilight: word %s for uid %s already exists") % (word, uid)) else: - sql = "INSERT INTO hilight(word, gid) VALUES('%s', '%s');" % (word, uid) - logger.debug(msg="createhilight: %s for gid %s" % (word, uid)) + sql = f"INSERT INTO hilight(word, gid) VALUES('{word}', '{uid}');" + logger.debug(msg=f"createhilight: {word} for gid {uid}") stampy.stampy.dbsql(sql) return True return False @@ -219,8 +208,8 @@ def deletehilight(word, uid): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM hilight WHERE word='%s' AND gid='%s';" % (word, uid) - logger.debug(msg="deletehilight: %s for uid %s" % (word, uid)) + sql = f"DELETE FROM hilight WHERE word='{word}' AND gid='{uid}';" + logger.debug(msg=f"deletehilight: {word} for uid {uid}") logger.debug(msg=sql) stampy.stampy.dbsql(sql) return True @@ -238,7 +227,7 @@ def listhilight(uid, word=False): wordtext = "" if not word: - sql = "select word from hilight WHERE gid='%s' ORDER BY word ASC;" % uid + sql = f"select word from hilight WHERE gid='{uid}' ORDER BY word ASC;" else: string = (word, uid) sql = "SELECT word FROM hilight WHERE word='%s' AND gid='%s' ORDER by word ASC;" % string @@ -283,11 +272,7 @@ def hilightwords(message): except: value = False - if value: - memberid = stampy.stampy.getitems(value[5]) - else: - memberid = [] - + memberid = stampy.stampy.getitems(value[5]) if value else [] for uid in uids: forward = False # Only forward if user is member of group diff --git a/stampy/plugin/info.py b/stampy/plugin/info.py index c4ffbb7..f3767fc 100644 --- a/stampy/plugin/info.py +++ b/stampy/plugin/info.py @@ -19,34 +19,31 @@ def init(): :return: List of triggers for plugin """ - triggers = ["^/info"] - return triggers + return ["^/info"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ msgdetail = stampy.stampy.getmsgdetail(message) - text = msgdetail["text"] - if text: - if text.split()[0].lower()[0:5] == "/info": + = msgdetail["text"]: + if text.split()[0].lower()[:5] == "/info": info(message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = _("Use `/info` to return information about the current message\n\n") - return commandtext + return _("Use `/info` to return information about the current message\n\n") def info(message): diff --git a/stampy/plugin/irccommands.py b/stampy/plugin/irccommands.py index 9b7ea2a..60bfc2a 100644 --- a/stampy/plugin/irccommands.py +++ b/stampy/plugin/irccommands.py @@ -20,10 +20,19 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/kick", "^/kickban", "^/unban", "^/op", "^/deop", - "^/topic", "^/mute", "^/unmute", "^/opall", "^/deopall", - "^/whois"] - return triggers + return [ + "^/kick", + "^/kickban", + "^/unban", + "^/op", + "^/deop", + "^/topic", + "^/mute", + "^/unmute", + "^/opall", + "^/deopall", + "^/whois", + ] def run(message): # do not edit this line @@ -297,7 +306,7 @@ def unban(chat_id=False, user_id=False): except: result = {'ok': False} - logger.debug(msg="RESULT: %s" % result) + logger.debug(msg=f"RESULT: {result}") if result['ok'] is True or result['ok'] == 'True': logger.info(msg=_L("User %s unbaned from %s") % (user_id, chat_id)) @@ -318,19 +327,23 @@ def op(chat_id=False, user_id=False, extra=""): result = {'ok': False} # Permissions as defined on API - permissions_base = ["can_change_info", "can_invite_users", "can_restrict_members", "can_promote_members"] + permissions_base = ["can_change_info", "can_invite_users", + "can_restrict_members", "can_promote_members"] permissions_group = permissions_base[:] permissions_group.extend(["can_delete_messages"]) permissions_channel = permissions_base[:] - permissions_channel.extend(["can_post_messages", "can_edit_messages", "can_delete_messages"]) + permissions_channel.extend( + ["can_post_messages", "can_edit_messages", "can_delete_messages"]) permissions_supergroup = permissions_base[:] permissions_supergroup.extend(["can_delete_messages", "can_pin_messages"]) - type, id, name, date, count, memberid = stampy.plugin.stats.getstats(id=chat_id) + type, id, name, date, count, memberid = stampy.plugin.stats.getstats( + id=chat_id) if not type: # Use API call for getting chat type if not in database - url = "%s%s/getChat?chat_id=%s" % (stampy.plugin.config.config(key='url'), stampy.plugin.config.config(key='token'), chat_id) + url = "%s%s/getChat?chat_id=%s" % (stampy.plugin.config.config( + key='url'), stampy.plugin.config.config(key='token'), chat_id) try: result = json.load(urllib.urlopen(url))['result']['type'] @@ -360,13 +373,13 @@ def op(chat_id=False, user_id=False, extra=""): break # Enable all permissions for OP operations - if extra == "" or extra == "op": + if extra in ["", "op"]: value = True elif extra == "deop": value = False if chat_id and user_id: for item in permissions: - extra = "%s&%s=%s" % (extra, item, value) + extra = f"{extra}&{item}={value}" url = "%s%s/promoteChatMember?chat_id=%s&user_id=%s&%s" % (stampy.plugin.config.config(key='url'), stampy.plugin.config.config(key='token'), chat_id, user_id, extra) try: @@ -430,7 +443,7 @@ def mute(chat_id=False, user_id=False, extra=""): permissions = ["can_send_messages", "can_send_media_messages", "can_send_other_messages", "can_add_web_page_previews"] # Enable all restrictions - if extra == "" or extra == "mute": + if extra in ["", "mute"]: value = False elif extra == "unmute": value = True @@ -440,7 +453,7 @@ def mute(chat_id=False, user_id=False, extra=""): if chat_id and user_id: # Iterate over permissions to set new value for item in permissions: - extra = "%s&%s=%s" % (extra, item, value) + extra = f"{extra}&{item}={value}" # For permissions we must assign all of them in a row or it will # reset other settings diff --git a/stampy/plugin/karma.py b/stampy/plugin/karma.py index 68182a3..c1eac64 100644 --- a/stampy/plugin/karma.py +++ b/stampy/plugin/karma.py @@ -22,11 +22,9 @@ def init(): :return: List of triggers for plugin """ - triggers = ["++", "--", u"—", "@", "^rank", "^srank", "^skarma", "==", "!="] - stampy.stampy.cronme(name="karma", interval=24 * 60) - return triggers + return ["++", "--", u"—", "@", "^rank", "^srank", "^skarma", "==", "!="] def cron(): @@ -38,14 +36,14 @@ def cron(): dokarmacleanup() -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: karmacommands(message) karmawords(message) return @@ -129,7 +127,7 @@ def karmacommands(message): stampy.stampy.sendmessage(chat_id=chat_id, text=commandtext, reply_to_message_id=message_id, parse_mode="Markdown") - logger.debug(msg="karmacommand: %s" % word) + logger.debug(msg=f"karmacommand: {word}") return @@ -165,7 +163,7 @@ def rank(word=False, gid=0): else: # if word is not provided, return top 10 words with top karma - sql = "select word,value,date from karma where gid='%s' ORDER BY value DESC LIMIT 10;" % gid + sql = f"select word,value,date from karma where gid='{gid}' ORDER BY value DESC LIMIT 10;" text = _("Global rankings:\n") cur = stampy.stampy.dbsql(sql) @@ -190,8 +188,8 @@ def srank(word=False, gid=0): # If no word is provided to srank, call rank instead text = rank(word) else: - string = "%" + "%s" % word + "%" - sql = "SELECT word,value,date FROM karma WHERE word LIKE '%s' AND gid='%s' LIMIT 10;" % (string, gid) + string = f"%{word}%" + sql = f"SELECT word,value,date FROM karma WHERE word LIKE '{string}' AND gid='{gid}' LIMIT 10;" cur = stampy.stampy.dbsql(sql) table = from_db_cursor(cur) text = "%s\n```%s```" % (text, table.get_string()) @@ -253,10 +251,10 @@ def putkarma(word, value, gid=0): date = datetime.datetime.now() datefor = date.strftime('%Y-%m-%d %H:%M:%S') - sql = "DELETE FROM karma WHERE word = '%s' AND gid='%s';" % (word, gid) + sql = f"DELETE FROM karma WHERE word = '{word}' AND gid='{gid}';" stampy.stampy.dbsql(sql) if value != 0: - sql = "INSERT INTO karma(word,value,date,gid) VALUES('%s','%s', '%s', '%s');" % (word, value, datefor, gid) + sql = f"INSERT INTO karma(word,value,date,gid) VALUES('{word}','{value}', '{datefor}', '{gid}');" stampy.stampy.dbsql(sql) logger.debug(msg=_L("Putting karma of %s to %s") % (value, word)) @@ -272,15 +270,15 @@ def stampyphant(chat_id="", karma=0): """ logger = logging.getLogger(__name__) - karma = "%s" % karma + karma = f"{karma}" # Sticker definitions for each rank x00 = "BQADBAADYwAD17FYAAEidrCCUFH7AgI" x000 = "BQADBAADZQAD17FYAAEeeRNtkOWfBAI" x0000 = "BQADBAADZwAD17FYAAHHuNL2oLuShwI" - x00000 = "BQADBAADaQAD17FYAAHzIBRZeY4uNAI" - sticker = "" if karma[-5:] == "00000": + x00000 = "BQADBAADaQAD17FYAAHzIBRZeY4uNAI" + sticker = x00000 elif karma[-4:] == "0000": sticker = x0000 @@ -292,7 +290,7 @@ def stampyphant(chat_id="", karma=0): text = _("Sticker for %s karma points") % karma if sticker != "": - stampy.stampy.sendsticker(chat_id=chat_id, sticker=sticker, text="%s" % text) + stampy.stampy.sendsticker(chat_id=chat_id, sticker=sticker, text=f"{text}") logger.debug(msg=text) return @@ -385,16 +383,12 @@ def karmaprocess(msgdetail): if len(word) >= 4: oper = word[-2:] word = word[:-2] - else: - # In case we've replied ++ or -- to a message, - # find username for it and add karma - - if len(word) == 2: - oper = word[-2:] - try: - word = msgdetail["replyto"].lower() - except: - word = False + elif len(word) == 2: + oper = word[-2:] + try: + word = msgdetail["replyto"].lower() + except: + word = False if word and oper: if stampy.plugin.alias.getalias(word, gid=gid): @@ -441,7 +435,8 @@ def karmaprocess(msgdetail): stampyphant(chat_id=chat_id, karma=karma) if messagetext != "": - stampy.stampy.sendmessage(chat_id=chat_id, text=messagetext, reply_to_message_id=message_id, parse_mode="Markdown") + stampy.stampy.sendmessage(chat_id=chat_id, text=messagetext, + reply_to_message_id=message_id, parse_mode="Markdown") return @@ -456,7 +451,7 @@ def dokarmacleanup(word=False, maxage=int(stampy.plugin.config.config("maxage", logger = logging.getLogger(__name__) if word: - sql = "SELECT word,value,date FROM karma WHERE word=%s" % word + sql = f"SELECT word,value,date FROM karma WHERE word={word}" else: sql = "SELECT word,value,date,gid FROM karma" diff --git a/stampy/plugin/quote.py b/stampy/plugin/quote.py index ebdbe0a..c6b553a 100644 --- a/stampy/plugin/quote.py +++ b/stampy/plugin/quote.py @@ -19,19 +19,18 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^/quote"] - return triggers + return ["^/quote"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:6] == "/quote": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:6] == "/quote": quotecommands(message) return @@ -64,7 +63,7 @@ def quotecommands(message): who_un = msgdetail["who_un"] logger = logging.getLogger(__name__) - logger.debug(msg="Command: %s by %s" % (texto, who_un)) + logger.debug(msg=f"Command: {texto} by {who_un}") # We might be have been given no command, just /quote try: @@ -114,15 +113,14 @@ def quotecommands(message): except: nick = False try: - (quoteid, username, date, quote) = getquote(username=nick, gid=stampy.stampy.geteffectivegid(gid=chat_id)) - datefor = datetime.datetime.fromtimestamp(float(date)).strftime('%Y-%m-%d %H:%M:%S') - text = '`%s` -- `@%s`, %s (id %s)' % ( - quote, username, datefor, quoteid) + (quoteid, username, date, quote) = getquote( + username=nick, gid=stampy.stampy.geteffectivegid(gid=chat_id)) + datefor = datetime.datetime.fromtimestamp( + float(date)).strftime('%Y-%m-%d %H:%M:%S') + text = f'`{quote}` -- `@{username}`, {datefor} (id {quoteid})' except: - if nick: - text = _("No quote recorded for `%s`") % nick - else: - text = _("No quote found") + text = _("No quote recorded for `%s`") % nick if nick else _( + "No quote found") stampy.stampy.sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True, @@ -144,10 +142,10 @@ def getquote(username=False, gid=0): string = (username, gid) sql = "SELECT id,username,date,text FROM quote WHERE username='%s' and gid='%s' ORDER BY RANDOM() LIMIT 1;" % string else: - sql = "SELECT id,username,date,text FROM quote WHERE gid='%s' ORDER BY RANDOM() LIMIT 1;" % gid + sql = f"SELECT id,username,date,text FROM quote WHERE gid='{gid}' ORDER BY RANDOM() LIMIT 1;" cur = stampy.stampy.dbsql(sql) value = cur.fetchone() - logger.debug(msg="getquote: %s for gid: %s" % (username, gid)) + logger.debug(msg=f"getquote: {username} for gid: {gid}") try: # Get value from SQL query (quoteid, username, date, quote) = value @@ -159,10 +157,7 @@ def getquote(username=False, gid=0): date = False quote = False - if quoteid: - return quoteid, username, date, quote - - return False + return (quoteid, username, date, quote) if quoteid else False def addquote(username=False, date=False, text=False, gid=0): @@ -176,15 +171,13 @@ def addquote(username=False, date=False, text=False, gid=0): """ logger = logging.getLogger(__name__) - sql = "INSERT INTO quote(username, date, text, gid) VALUES('%s','%s', '%s', '%s');" % ( - username, date, text, gid) + sql = f"INSERT INTO quote(username, date, text, gid) VALUES('{username}','{date}', '{text}', '{gid}');" cur = stampy.stampy.dbsql(sql) logger.debug(msg=_L("createquote: %s=%s on %s for group %s") % (username, text, date, gid)) # Retrieve last id sql = "select last_insert_rowid();" cur = stampy.stampy.dbsql(sql) - lastrowid = cur.fetchone()[0] - return lastrowid + return cur.fetchone()[0] def deletequote(id=False, gid=0): @@ -196,6 +189,6 @@ def deletequote(id=False, gid=0): """ logger = logging.getLogger(__name__) - sql = "DELETE FROM quote WHERE id='%s' AND gid='%s';" % (id, gid) - logger.debug(msg="deletequote: %s, group: %s" % (id, gid)) + sql = f"DELETE FROM quote WHERE id='{id}' AND gid='{gid}';" + logger.debug(msg=f"deletequote: {id}, group: {gid}") return stampy.stampy.dbsql(sql) diff --git a/stampy/plugin/remedar.py b/stampy/plugin/remedar.py index bedc55c..12a950a 100644 --- a/stampy/plugin/remedar.py +++ b/stampy/plugin/remedar.py @@ -20,9 +20,7 @@ def init(): :return: List of triggers for plugin """ - triggers = ["*"] - - return triggers + return ["*"] def cron(): @@ -32,26 +30,25 @@ def cron(): """ -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: replacevowels(message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = "" - return commandtext + return "" def replacevowels(message): @@ -81,7 +78,7 @@ def replacevowels(message): if texto != '' and doremedar: text = re.sub("[aeouAEOUáéóúàèòùäëöü]", "i", texto) if texto != text: - logger.info("Remedar for %s in chat %s" % (who_id, chat_id)) + logger.info(f"Remedar for {who_id} in chat {chat_id}") stampy.stampy.sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True, diff --git a/stampy/plugin/stats.py b/stampy/plugin/stats.py index fc25d13..c2a10c0 100644 --- a/stampy/plugin/stats.py +++ b/stampy/plugin/stats.py @@ -24,11 +24,9 @@ def init(): :return: List of triggers for plugin """ - triggers = ["@all", "^/stats", "*", "^/getout"] - stampy.stampy.cronme(name="stats", interval=24 * 60) - return triggers + return ["@all", "^/stats", "*", "^/getout"] def cron(): @@ -41,7 +39,7 @@ def cron(): dousercleanup() -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -67,9 +65,9 @@ def run(message): # do not edit this line memberid=msgdetail["chat_id"]) if text: - if text.split()[0].lower()[0:6] == "/stats": + if text.split()[0].lower()[:6] == "/stats": statscommands(message) - elif text.split()[0].lower()[0:7] == "/getout": + elif text.split()[0].lower()[:7] == "/getout": getoutcommands(message) if "@all" in text: @@ -249,19 +247,19 @@ def showstats(type=False, name=None, key="name"): """ logger = logging.getLogger(__name__) if type: - sql = "select type,id,name,date,count from stats WHERE type='%s'" % type + sql = f"select type,id,name,date,count from stats WHERE type='{type}'" if name: - string = "%" + "%s" % name + "%" - sql = sql + " and " + key + "like '%s'" % string + string = f"%{name}%" + sql = f"{sql} and {key}" + f"like '{string}'" else: sql = "select type,id,name,date,count from stats" if name: - string = "%" + "%s" % name + "%" - sql = sql + " WHERE " + key + " like '%s'" % string + string = f"%{name}%" + sql = f"{sql} WHERE {key}" + f" like '{string}'" - sql = sql + " ORDER BY count DESC LIMIT 10" + sql = f"{sql} ORDER BY count DESC LIMIT 10" cur = stampy.stampy.dbsql(sql) table = from_db_cursor(cur) @@ -293,11 +291,7 @@ def updatestats(type=False, id=0, name=False, date=False, memberid=None): value = False count = 0 - if value: - newmemberid = value[5] - else: - newmemberid = [] - + newmemberid = value[5] if value else [] # Only add the id if it was not already stored if memberid not in newmemberid: if memberid is list: @@ -318,10 +312,10 @@ def updatestats(type=False, id=0, name=False, date=False, memberid=None): if [] in newmemberid: newmemberid.remove([]) - sql = "DELETE from stats where id='%s'" % id + sql = f"DELETE from stats where id='{id}'" stampy.stampy.dbsql(sql) - sql = "INSERT INTO stats(type, id, name, date, count, memberid) VALUES('%s', '%s', '%s', '%s', '%s', '%s');" % (type, id, name, date, count, json.dumps(newmemberid)) + sql = f"INSERT INTO stats(type, id, name, date, count, memberid) VALUES('{type}', '{id}', '{name}', '{date}', '{count}', '{json.dumps(newmemberid)}');" logger.debug(msg=_L("values: type:%s, id:%s, name:%s, date:%s, count:%s, memberid: %s") % (type, id, name, date, count, newmemberid)) @@ -355,11 +349,7 @@ def remove_from_memberid(type=False, id=0, name=False, date=False, memberid=None value = False count = 0 - if value: - newmemberid = value[5] - else: - newmemberid = [] - + newmemberid = value[5] if value else [] # Only add the id if it was not already stored if memberid in newmemberid: newmemberid.remove(memberid) @@ -377,10 +367,10 @@ def remove_from_memberid(type=False, id=0, name=False, date=False, memberid=None if [] in newmemberid: newmemberid.remove([]) - sql = "DELETE from stats where id='%s'" % id + sql = f"DELETE from stats where id='{id}'" stampy.stampy.dbsql(sql) - sql = "INSERT INTO stats(type, id, name, date, count, memberid) VALUES('%s', '%s', '%s', '%s', '%s', '%s');" % (type, id, name, date, count, json.dumps(newmemberid)) + sql = f"INSERT INTO stats(type, id, name, date, count, memberid) VALUES('{type}', '{id}', '{name}', '{date}', '{count}', '{json.dumps(newmemberid)}');" logger.debug(msg=_L("values: type:%s, id:%s, name:%s, date:%s, count:%s, memberid: %s") % (type, id, name, date, count, newmemberid)) @@ -441,7 +431,7 @@ def dochatcleanup(chat_id=False, maxage=False): logger = logging.getLogger(__name__) if chat_id: - sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE type <> 'private' and id=%s" % chat_id + sql = f"SELECT type,id,name,date,count,memberid FROM stats WHERE type <> 'private' and id={chat_id}" else: sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE type <> 'private'" @@ -483,28 +473,25 @@ def dochatcleanup(chat_id=False, maxage=False): newmaster = 0 maxmembers = 0 - sql = "SELECT id from config WHERE key='link' and value='%s'" % chatid + sql = f"SELECT id from config WHERE key='link' and value='{chatid}'" cur = stampy.stampy.dbsql(sql) for row in cur.fetchall(): id = row[0] - value = getstats(id=id) - if value: - newmemberid = value[5] - else: - newmemberid = [] - + newmemberid = value[5] if (value: = getstats(id=id)) else [] if len(newmemberid) > maxmembers: maxmembers = len(newmemberid) newmaster = id if newmaster != 0: - logger.debug(msg=_L("The removed channel (%s) was master for others, electing new master: %s") % (chatid, newmaster)) + logger.debug(msg=_L("The removed channel (%s) was master for others, electing new master: %s") % ( + chatid, newmaster)) # Update slaves to new master - sql = "UPDATE config SET value='%s' WHERE key='link' and value='%s'" % (newmaster, chatid) + sql = f"UPDATE config SET value='{newmaster}' WHERE key='link' and value='{chatid}'" cur = stampy.stampy.dbsql(sql) - migratechats(oldchat=chat_id, newchat=newmaster, includeall=False) + migratechats(oldchat=chat_id, newchat=newmaster, + includeall=False) # Remove 'link' from the new master so it becomes a master stampy.plugin.config.deleteconfig(key='link', gid=newmaster) @@ -512,17 +499,17 @@ def dochatcleanup(chat_id=False, maxage=False): # Two different names because of historical reasons for table in ['config', 'stats']: # Remove channel stats - sql = "DELETE from %s where id='%s';" % (table, chatid) + sql = f"DELETE from {table} where id='{chatid}';" cur = stampy.stampy.dbsql(sql) for table in ['karma', 'quote', 'autokarma', 'alias', 'feeds']: # Remove channel stats - sql = "DELETE from %s where gid='%s';" % (table, chatid) + sql = f"DELETE from {table} where gid='{chatid}';" cur = stampy.stampy.dbsql(sql) # Remove users membership that had that channel id - string = "%" + "%s" % chatid + "%" - sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE type='user' and memberid LIKE '%s';" % string + string = f"%{chatid}%" + sql = f"SELECT type,id,name,date,count,memberid FROM stats WHERE type='user' and memberid LIKE '{string}';" cur = stampy.stampy.dbsql(sql) for line in cur: @@ -550,25 +537,24 @@ def migratechats(oldchat, newchat, includeall=True): # move data from old master to new one (except stats and config) logger.debug(msg=_L("Migrating chat id: %s to %s") % (oldchat, newchat)) for table in ['karma', 'quote', 'autokarma', 'alias', 'feeds']: - sql = "UPDATE %s SET gid='%s' where gid='%s';" % (table, newchat, oldchat) + sql = f"UPDATE {table} SET gid='{newchat}' where gid='{oldchat}';" stampy.stampy.dbsql(sql) if includeall: for table in ['config', 'stats']: - sql = "UPDATE %s SET id='%s' where id='%s';" % (table, newchat, oldchat) + sql = f"UPDATE {table} SET id='{newchat}' where id='{oldchat}';" stampy.stampy.dbsql(sql) # Migrate forward data - sql = "UPDATE forward SET source='%s' where source='%s';" % (newchat, oldchat) - stampy.stampy.dbsql(sql) - sql = "UPDATE forward SET target='%s' where target='%s';" % (newchat, oldchat) + sql = f"UPDATE forward SET source='{newchat}' where source='{oldchat}';" stampy.stampy.dbsql(sql) + sql = f"UPDATE forward SET target='{newchat}' where target='{oldchat}';" else: # Delete forwards not migrated - sql = "DELETE FROM forward WHERE source='%s';" % oldchat - stampy.stampy.dbsql(sql) - sql = "DELETE FROM forward WHERE target='%s';" % oldchat + sql = f"DELETE FROM forward WHERE source='{oldchat}';" stampy.stampy.dbsql(sql) + sql = f"DELETE FROM forward WHERE target='{oldchat}';" + stampy.stampy.dbsql(sql) return @@ -582,7 +568,7 @@ def dousercleanup(user_id=False, maxage=int(stampy.plugin.config.config("maxage" logger = logging.getLogger(__name__) if user_id: - sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE type='user' and id=%s" % user_id + sql = f"SELECT type,id,name,date,count,memberid FROM stats WHERE type='user' and id={user_id}" else: sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE type='user'" @@ -610,11 +596,11 @@ def dousercleanup(user_id=False, maxage=int(stampy.plugin.config.config("maxage" userid, name, (now - chatdate).days)) # Remove channel stats - sql = "DELETE from stats where id='%s';" % userid + sql = f"DELETE from stats where id='{userid}';" cur = stampy.stampy.dbsql(sql) # Remove hilights - sql = "DELETE from hilight where gid='%s';" % userid + sql = f"DELETE from hilight where gid='{userid}';" cur = stampy.stampy.dbsql(sql) # Remove users membership that had that channel id @@ -623,10 +609,12 @@ def dousercleanup(user_id=False, maxage=int(stampy.plugin.config.config("maxage" for line in cur: (type, id, name, date, count, memberid) = line - logger.debug(msg=_L("LINE for user %s and memberid: %s will be deleted") % (name, memberid)) + logger.debug( + msg=_L("LINE for user %s and memberid: %s will be deleted") % (name, memberid)) memberid.remove(userid) # Update stats entry in database without the removed chat - updatestats(type=type, id=id, name=name, date=date, memberid=memberid) + updatestats(type=type, id=id, name=name, + date=date, memberid=memberid) # Check if user was admin for any channel, and remove username = None @@ -636,8 +624,8 @@ def dousercleanup(user_id=False, maxage=int(stampy.plugin.config.config("maxage" username = each[1:-1] if username and username != "@": # userid to remove has username, check admins on config and remove - string = "%" + username + "%" - sql = "SELECT id, value FROM config WHERE value like %s" % string + string = f"%{username}%" + sql = f"SELECT id, value FROM config WHERE value like {string}" cur = stampy.stampy.dbsql(sql) @@ -648,9 +636,8 @@ def dousercleanup(user_id=False, maxage=int(stampy.plugin.config.config("maxage" admins.remove(username) except: pass - newadmin = " ".join(admins) - - if len(newadmin) != 0: + if newadmin: + = " ".join(admins): stampy.plugin.config.setconfig(key='admin', value=newadmin, gid=id) else: @@ -671,9 +658,9 @@ def getstats(type=False, id=0, name=False, date=False, count=0): """ logger = logging.getLogger(__name__) - sql = "SELECT type,id,name,date,count,memberid FROM stats WHERE id='%s'" % id + sql = f"SELECT type,id,name,date,count,memberid FROM stats WHERE id='{id}'" if type: - sql = "%s%s" % (sql, " AND type='%s';" % type) + sql = f"{sql} AND type='{type}';" cur = stampy.stampy.dbsql(sql) try: value = cur.fetchone() @@ -727,11 +714,8 @@ def getall(message): all.append(username) if "@all++" in texto: - text = "" - newall = [] - for each in all: - newall.append("%s++" % each) - text += " ".join(newall) + newall = [f"{each}++" for each in all] + text = "" + " ".join(newall) msgdetail["text"] = text if newall and text: stampy.plugin.karma.karmaprocess(msgdetail) @@ -764,24 +748,19 @@ def pingchat(chatid): def idfromuser(idorname=False, chat_id=False): logger = logging.getLogger(__name__) - string = "%" + "%s" % idorname + "%" - sql = "select id,name from stats where (name like '%s' or id like '%s')" % (string, string) + string = f"%{idorname}%" + sql = f"select id,name from stats where (name like '{string}' or id like '{string}')" if chat_id: - string = "%" + "%s" % chat_id + "%" - sql = sql + " and memberid like '%s'" % string + string = f"%{chat_id}%" + sql = f"{sql} and memberid like '{string}'" - sql = sql + ";" + sql = f"{sql};" # Find user ID provided in database for current channel cur = stampy.stampy.dbsql(sql) - results = [] - - for row in cur: - # Process each word returned - results.append({"id": row[0], "name": row[1]}) - + results = [{"id": row[0], "name": row[1]} for row in cur] logger.debug(msg=_L("Found users with id(%s)/chat(%s): %s") % (idorname, chat_id, results)) return results diff --git a/stampy/plugin/stock.py b/stampy/plugin/stock.py index 0ed9d4e..d6aea00 100644 --- a/stampy/plugin/stock.py +++ b/stampy/plugin/stock.py @@ -22,31 +22,29 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["^stock"] - return triggers + return ["^stock"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ - text = stampy.stampy.getmsgdetail(message)["text"] if text: + = stampy.stampy.getmsgdetail(message)["text"]: if text.split()[0].lower() == "stock": stock(message=message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = _("Use `stock ` to get stock trading price\n\n") - return commandtext + return _("Use `stock ` to get stock trading price\n\n") class IEXAPI: @@ -54,7 +52,7 @@ def __init__(self): self.prefix = "https://api.iextrading.com/1.0/stock/" def get(self, symbol): - url = self.prefix + "%s/quote" % symbol + url = f"{self.prefix}{symbol}/quote" content = json.loads(requests.get(url).content) quote = {'t': symbol} if "change" in content: @@ -114,7 +112,7 @@ def stock(message): message_id = msgdetail["message_id"] who_un = msgdetail["who_un"] - logger.debug(msg=_L("Command: %s by %s" % (texto, who_un))) + logger.debug(msg=_L(f"Command: {texto} by {who_un}")) # We might be have been given no command, just stock try: @@ -123,21 +121,26 @@ def stock(message): command = False if not command: - stock = stampy.plugin.config.gconfig(key="stock", default="RHT", gid=chat_id).split(" ") + stock = stampy.plugin.config.gconfig( + key="stock", default="RHT", gid=chat_id).split(" ") else: stock = texto.split(" ")[1::] text = "```\n" - currency = stampy.plugin.config.gconfig(key="currency", default="EUR", gid=chat_id) - if currency != 'USD': - rate = get_currency_rate('USD', currency) - else: - rate = 1 - text += _("USD/%s rate " % currency + str(rate) + "\n") + currency = stampy.plugin.config.gconfig( + key="currency", default="EUR", gid=chat_id) + rate = get_currency_rate('USD', currency) if currency != 'USD' else 1 + text += _(f"USD/{currency} rate {str(rate)}" + "\n") for ticker in stock: try: quote = c.get(ticker.upper()) - text += "%s Quote " % quote["t"] + " " + str(quote["l_cur"]) + " " + str(quote["c"]) + " (%s%%)" % str(quote["cp"]) + text += ( + f'{quote["t"]} Quote ' + + str(quote["l_cur"]) + + " " + + str(quote["c"]) + + " (%s%%)" % str(quote["cp"]) + ) quoteUSD = quote["l_cur"] quoteEur = float(quoteUSD * rate) text += " (%s %s)\n" % ("{0:.2f}".format(quoteEur), currency) diff --git a/stampy/plugin/sudo.py b/stampy/plugin/sudo.py index 9ddab0f..52bc8d6 100644 --- a/stampy/plugin/sudo.py +++ b/stampy/plugin/sudo.py @@ -22,11 +22,10 @@ def init(): stampy.plugin.config.deleteconfig(key='overridegid', gid='0') stampy.plugin.config.deleteconfig(key='sudo', gid='0') - triggers = ["^/sudo"] - return triggers + return ["^/sudo"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against @@ -34,9 +33,9 @@ def run(message): # do not edit this line """ logger = logging.getLogger(__name__) logger.debug(msg=_L("Processing plugin: Code: %s") % __file__) - text = stampy.stampy.getmsgdetail(message)["text"] if text: - if text.split()[0].lower()[0:6] == "/sudo": + = stampy.stampy.getmsgdetail(message)["text"]: + if text.split()[0].lower()[:6] == "/sudo": sudocommands(message) return @@ -98,31 +97,35 @@ def sudocommands(message): reply_to_message_id=message_id, disable_web_page_preview=True, parse_mode="Markdown") - if value != "": - stampy.plugin.config.setconfig(key='sudo', value=value, gid=0) + if value == "": + stampy.plugin.config.deleteconfig( + key='sudo', gid=0) else: - stampy.plugin.config.deleteconfig(key='sudo', gid=0) - else: - if stampy.plugin.config.config(key='sudo'): - # "=" was not in first command, so consider a command to use as 'sudo' - - # It is a new list, with unique message, so we can alter it - stampy.plugin.config.setconfig(key='overridegid', gid=0, value=message['message']['chat']['id']) - newmessage = dict(message) - - # Alter chat ID - newmessage['message']['chat']['id'] = int(stampy.plugin.config.config(key='sudo')) - - # Alter message text - type = msgdetail["type"] - newmessage[type]['text'] = newmessage[type]['text'][6:] - - # Alter who_id and who_un - newmessage[type]['from']['id'] = int(stampy.plugin.config.config(key='sudo')) - - newmessages = [] - newmessages.append(newmessage) - # Process the new mangled message as if it was sent to a telegram chat - stampy.stampy.process(messages=newmessages) - stampy.plugin.config.deleteconfig(key='overridegid', gid='0') + stampy.plugin.config.setconfig( + key='sudo', value=value, gid=0) + elif stampy.plugin.config.config(key='sudo'): + # "=" was not in first command, so consider a command to use as 'sudo' + + # It is a new list, with unique message, so we can alter it + stampy.plugin.config.setconfig( + key='overridegid', gid=0, value=message['message']['chat']['id']) + newmessage = dict(message) + + # Alter chat ID + newmessage['message']['chat']['id'] = int( + stampy.plugin.config.config(key='sudo')) + + # Alter message text + type = msgdetail["type"] + newmessage[type]['text'] = newmessage[type]['text'][6:] + + # Alter who_id and who_un + newmessage[type]['from']['id'] = int( + stampy.plugin.config.config(key='sudo')) + + newmessages = [newmessage] + # Process the new mangled message as if it was sent to a telegram chat + stampy.stampy.process(messages=newmessages) + stampy.plugin.config.deleteconfig( + key='overridegid', gid='0') return diff --git a/stampy/plugin/uptime.py b/stampy/plugin/uptime.py index 5d61e5e..95cd0fd 100644 --- a/stampy/plugin/uptime.py +++ b/stampy/plugin/uptime.py @@ -23,38 +23,36 @@ def init(): :return: List of triggers for plugin """ - triggers = ["^/uptime"] - # Store initialization time as 'bot start time' date = stampy.stampy.utize(datetime.datetime.now()) stampy.plugin.config.setconfig(key='uptime', gid=0, value=date) - return triggers + return ["^/uptime"] -def run(message): # do not edit this line +def run(message): # do not edit this line """ Executes plugin :param message: message to run against :return: """ msgdetail = stampy.stampy.getmsgdetail(message) - text = msgdetail["text"] - if text: - if text.split()[0].lower()[0:7] == "/uptime": + = msgdetail["text"]: + if text.split()[0].lower()[:7] == "/uptime": uptime(message) return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = _("Use `/uptime` to return information about running time of the bot\n\n") - return commandtext + return _( + "Use `/uptime` to return information about running time of the bot\n\n" + ) def uptime(message): diff --git a/stampy/plugin/welcome.py b/stampy/plugin/welcome.py index 47a2791..7bd60fe 100644 --- a/stampy/plugin/welcome.py +++ b/stampy/plugin/welcome.py @@ -17,8 +17,7 @@ def init(): Initializes module :return: List of triggers for plugin """ - triggers = ["*"] - return triggers + return ["*"] def run(message): # do not edit this line @@ -37,17 +36,20 @@ def run(message): # do not edit this line return -def help(message): # do not edit this line +def help(message): # do not edit this line """ Returns help for plugin :param message: message to process :return: help text """ - commandtext = "" - if stampy.stampy.is_owner_or_admin(message): - commandtext = _("As admin or owner define 'welcome' to the greeting text sent to new chat members. You can use $username to put long name in the text\n\n") - return commandtext + return ( + _( + "As admin or owner define 'welcome' to the greeting text sent to new chat members. You can use $username to put long name in the text\n\n" + ) + if stampy.stampy.is_owner_or_admin(message) + else "" + ) def welcomeuser(message): @@ -83,7 +85,7 @@ def welcomeuser(message): except: newlastname = "" - name = "%s %s ([`@%s`](https://t.me/%s))" % (newfirstname, newlastname, newusername, newusername) + name = f"{newfirstname} {newlastname} ([`@{newusername}`](https://t.me/{newusername}))" greeting = welcome.replace("$username", name) diff --git a/stampy/plugins.py b/stampy/plugins.py index b378475..c238b65 100644 --- a/stampy/plugins.py +++ b/stampy/plugins.py @@ -68,9 +68,7 @@ def initplugins(): logger.debug(msg=_L("Processing plugin initialization: %s") % i["name"]) newplug = loadPlugin(i) plugs.append(newplug) - triggers = [] - for each in newplug.init(): - triggers.append(each) + triggers = list(newplug.init()) plugtriggers[i["name"]] = triggers logger.debug(msg=_L("Plugin %s is triggered by %s") % (i["name"], triggers)) return plugs, plugtriggers diff --git a/stampy/stampy.py b/stampy/stampy.py index e87fe62..70e01c9 100755 --- a/stampy/stampy.py +++ b/stampy/stampy.py @@ -108,8 +108,11 @@ def createorupdatedb(): import alembic.config alembicArgs = [ - '-x', 'database=%s' % options.database, '--raiseerr', - 'upgrade', 'head', + '-x', + f'database={options.database}', + '--raiseerr', + 'upgrade', + 'head', ] logger.debug(msg=_L("Using alembic to upgrade/create database to expected revision")) @@ -191,14 +194,10 @@ def sendmessage(chat_id=0, text="", reply_to_message_id=False, maxlines = 15 if len(lines) > maxlines: # message might be too big for single message (max 4K) - if "```" in text: - markdown = True - else: - markdown = False - - texto = string.join(lines[0:maxlines], "\n") + markdown = "```" in text + texto = string.join(lines[:maxlines], "\n") if markdown: - texto = "%s```" % texto + texto = f"{texto}```" # Send first batch sendmessage(chat_id=chat_id, text=texto, @@ -208,29 +207,29 @@ def sendmessage(chat_id=0, text="", reply_to_message_id=False, # Send remaining batch texto = string.join(lines[maxlines:], "\n") if markdown: - texto = "```%s" % texto + texto = f"```{texto}" sendmessage(chat_id=chat_id, text=texto, reply_to_message_id=False, disable_web_page_preview=disable_web_page_preview, parse_mode=parse_mode, extra=extra) return - overridegid = plugin.config.config(key='overridegid', gid=0, - default=False) if overridegid: + = plugin.config.config( + key='overridegid', gid=0, default=False + ): chat_id = overridegid - message = "%s?chat_id=%s&text=%s" % ( - url, chat_id, urllib.quote_plus(text.encode('utf-8'))) + message = f"{url}?chat_id={chat_id}&text={urllib.quote_plus(text.encode('utf-8'))}" if reply_to_message_id: - message += "&reply_to_message_id=%s" % reply_to_message_id + message += f"&reply_to_message_id={reply_to_message_id}" if disable_web_page_preview: message += "&disable_web_page_preview=1" else: message += "&disable_web_page_preview=0" if parse_mode: - message += "&parse_mode=%s" % parse_mode + message += f"&parse_mode={parse_mode}" if extra: - message += "&%s" % extra + message += f"&{extra}" code = False attempt = 0 @@ -321,7 +320,7 @@ def deletemessage(chat_id=0, message_id=False): logger = logging.getLogger(__name__) url = "%s%s/deleteMessage" % (plugin.config.config(key="url"), plugin.config.config(key='token')) - message = "%s?chat_id=%s&message_id=%s" % (url, chat_id, message_id) + message = f"{url}?chat_id={chat_id}&message_id={message_id}" code = False attempt = 0 @@ -377,10 +376,10 @@ def getupdates(offset=0, limit=100): logger = logging.getLogger(__name__) url = "%s%s/getUpdates" % (plugin.config.config(key='url'), plugin.config.config(key='token')) - message = "%s?" % url + message = f"{url}?" if offset != 0: - message += "offset=%s&" % offset - message += "limit=%s" % limit + message += f"offset={offset}&" + message += f"limit={limit}" try: result = json.load(urllib.urlopen(message))['result'] except: @@ -402,7 +401,7 @@ def getme(): url = "%s%s/getMe" % (plugin.config.config(key='url'), plugin.config.config(key='token')) - message = "%s" % url + message = f"{url}" try: result = json.load(urllib.urlopen(message))['result']['username'] except: @@ -426,8 +425,8 @@ def clearupdates(offset): logger = logging.getLogger(__name__) url = "%s%s/getUpdates" % (plugin.config.config(key='url'), plugin.config.config(key='token')) - message = "%s?" % url - message += "offset=%s&" % offset + message = f"{url}?" + message += f"offset={offset}&" try: result = json.load(urllib.urlopen(message)) except: @@ -448,10 +447,10 @@ def sendsticker(chat_id=0, sticker="", text="", reply_to_message_id=""): logger = logging.getLogger(__name__) url = "%s%s/sendSticker" % (plugin.config.config(key='url'), plugin.config.config(key='token')) - message = "%s?chat_id=%s" % (url, chat_id) - message = "%s&sticker=%s" % (message, sticker) + message = f"{url}?chat_id={chat_id}" + message = f"{message}&sticker={sticker}" if reply_to_message_id: - message += "&reply_to_message_id=%s" % reply_to_message_id + message += f"&reply_to_message_id={reply_to_message_id}" logger.debug(msg=_L("Sending sticker: %s") % text) # It this is executed as per unit testing, skip sending message @@ -633,19 +632,29 @@ def getmsgdetail(message): except: who_un = "" - name = "%s %s (@%s)" % (who_gn, who_ln, who_un) + name = f"{who_gn} {who_ln} (@{who_un})" while " " in name: name = name.replace(" ", " ") - # args = ('name', 'chat_id', 'chat_name', 'date', 'datefor', 'error', 'message_id', - # 'text', 'update_id', 'who_gn', 'who_id', 'who_ln', 'who_un') - # vals = dict((k, v) for (k, v) in locals().iteritems() if k in args) - - vals = {"name": name, "chat_id": chat_id, "chat_name": chat_name, "date": date, "datefor": datefor, "error": error, - "message_id": message_id, "text": text, "update_id": update_id, "who_gn": who_gn, "who_id": who_id, - "who_ln": who_ln, "who_un": who_un, "type": type, "replyto": replyto, "replytotext": replytotext, "chat_type": chat_type} - - return vals + return { + "name": name, + "chat_id": chat_id, + "chat_name": chat_name, + "date": date, + "datefor": datefor, + "error": error, + "message_id": message_id, + "text": text, + "update_id": update_id, + "who_gn": who_gn, + "who_id": who_id, + "who_ln": who_ln, + "who_un": who_un, + "type": type, + "replyto": replyto, + "replytotext": replytotext, + "chat_type": chat_type, + } def process(messages): @@ -680,7 +689,8 @@ def process(messages): botname = getme() # Write the line for debug - messageline = _L("TEXT: %s : %s : %s") % (msgdetail["chat_name"], msgdetail["name"], msgdetail["text"]) + messageline = _L("TEXT: %s : %s : %s") % ( + msgdetail["chat_name"], msgdetail["name"], msgdetail["text"]) logger.debug(msg=messageline) # Process group configuration for language @@ -688,7 +698,7 @@ def process(messages): chlang(lang=plugin.config.gconfig(key='language', gid=chat_id)) try: - command = msgdetail["text"].split()[0].lower().replace('@%s' % botname, '') + command = msgdetail["text"].split()[0].lower().replace(f'@{botname}', '') texto = msgdetail["text"].lower() date = msgdetail["datefor"] except: @@ -699,19 +709,15 @@ def process(messages): for i in plugs: name = i.__name__.split(".")[-1] - runplugin = False - for trigger in plugtriggers[name]: - if "*" in trigger: - runplugin = True - break - elif trigger[0] == "^": - if command == trigger[1:]: - runplugin = True - break - elif trigger in texto: - runplugin = True - break - + runplugin = any( + "*" not in trigger + and trigger[0] == "^" + and command == trigger[1:] + or "*" in trigger + or trigger[0] != "^" + and trigger in texto + for trigger in plugtriggers[name] + ) code = False if runplugin: logger.debug(msg=_L("Processing plugin: %s") % name) @@ -784,7 +790,7 @@ def shouldrun(name): :return: Bool """ - sql = "SELECT name,lastchecked,interval from cron where name='%s'" % name + sql = f"SELECT name,lastchecked,interval from cron where name='{name}'" cur = dbsql(sql) date = utize(datetime.datetime.now()) @@ -820,14 +826,10 @@ def shouldrun(name): # If more time has passed since last check than the interval for # checks, run the check - if timediff < interval: - code = False - else: - code = True - + code = timediff >= interval # Update db with results if code: - sql = "UPDATE cron SET lastchecked='%s' where name='%s'" % (datefor, name) + sql = f"UPDATE cron SET lastchecked='{datefor}' where name='{name}'" logger.debug(msg=_L("Updating last checked as per %s") % sql) dbsql(sql=sql) return code @@ -842,9 +844,9 @@ def cronme(name=False, interval=5): """ if name: - sql = "DELETE from cron WHERE name='%s'" % name + sql = f"DELETE from cron WHERE name='{name}'" dbsql(sql=sql) - sql = "INSERT INTO cron(name,interval) VALUES('%s', '%s')" % (name, interval) + sql = f"INSERT INTO cron(name,interval) VALUES('{name}', '{interval}')" dbsql(sql=sql) @@ -884,12 +886,11 @@ def is_owner(message): """ logger = logging.getLogger(__name__) - code = False msgdetail = getmsgdetail(message) - for each in plugin.config.config(key='owner').split(" "): - if each == msgdetail["who_un"]: - code = True - return code + return any( + each == msgdetail["who_un"] + for each in plugin.config.config(key='owner').split(" ") + ) def is_owner_or_admin(message, strict=False): @@ -924,10 +925,10 @@ def is_owner_or_admin(message, strict=False): admin = True logger.debug(msg=_L("We're admin of public chat")) - # If we're not admin and admin is empty, consider ourselves admin - if not admin: - if plugin.config.config(key='admin', gid=chat_id, default="") == "": - logger.debug(msg=_L("We're admin because no admin listed on public chat")) + if plugin.config.config(key='admin', gid=chat_id, default="") == "": + if not admin: + logger.debug( + msg=_L("We're admin because no admin listed on public chat")) admin = True return owner or admin @@ -940,21 +941,16 @@ def geteffectivegid(gid): :return: gid to use """ - if plugin.config.gconfig(key='isolated', default=False, gid=gid): - # Isolated is defined for either channel or general bot config. - # need to check now if group is linked and if so, return that gid, - # and if not, return groupid - - link = plugin.config.gconfig(key='link', default=False, gid=gid) - if link: + if not plugin.config.gconfig(key='isolated', default=False, gid=gid): + # Non isolation configured, returning '0' as gid to use + return 0 + if link: + = plugin.config.gconfig(key='link', default=False, gid=gid): # This chat_id has 'link' defined against master, effective gid # should be that one - return int(link) - else: - return gid + return int(link) else: - # Non isolation configured, returning '0' as gid to use - return 0 + return gid def loglevel():