Commit accf6181 authored by zeroone2numeral2's avatar zeroone2numeral2
Browse files

Tabs to spaces

parent 5eb36bc7
...@@ -9,19 +9,19 @@ logger = logging.getLogger(__name__) ...@@ -9,19 +9,19 @@ logger = logging.getLogger(__name__)
@run_async @run_async
def error_callback(bot, update, error): def error_callback(bot, update, error):
pass # p-t-b's logger already logs this to the console pass # p-t-b's logger already logs this to the console
def main(): def main():
for modname in ["sed", "help", "yesno"]: for modname in ["sed", "help", "yesno"]:
module = getattr(importlib.import_module('bot.modules.{}'.format(modname)), "module") module = getattr(importlib.import_module('bot.modules.{}'.format(modname)), "module")
logger.info("module imported: %s (handlers: %d)", module.name, len(module.handlers)) logger.info("module imported: %s (handlers: %d)", module.name, len(module.handlers))
for handler in module.handlers: for handler in module.handlers:
dispatcher.add_handler(handler) dispatcher.add_handler(handler)
dispatcher.add_error_handler(error_callback) dispatcher.add_error_handler(error_callback)
updater.start_polling(clean=True) updater.start_polling(clean=True)
updater.idle() updater.idle()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
\ No newline at end of file \ No newline at end of file
...@@ -2,11 +2,11 @@ from telegram.ext import Filters ...@@ -2,11 +2,11 @@ from telegram.ext import Filters
from telegram.ext import BaseFilter from telegram.ext import BaseFilter
class _Reply_text(BaseFilter): class _Reply_text(BaseFilter):
name = 'Filters.reply_text' name = 'Filters.reply_text'
def filter(self, message): def filter(self, message):
if message.reply_to_message: if message.reply_to_message:
return bool(message.reply_to_message.text or message.reply_to_message.caption) return bool(message.reply_to_message.text or message.reply_to_message.caption)
return False return False
Filters.reply_text = _Reply_text() Filters.reply_text = _Reply_text()
...@@ -3,26 +3,26 @@ from telegram import Update ...@@ -3,26 +3,26 @@ from telegram import Update
from telegram.ext import RegexHandler from telegram.ext import RegexHandler
class FilteredRegexHandler(RegexHandler): class FilteredRegexHandler(RegexHandler):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.filters = kwargs.pop("filters") self.filters = kwargs.pop("filters")
RegexHandler.__init__(self, *args, **kwargs) RegexHandler.__init__(self, *args, **kwargs)
def check_update(self, update): def check_update(self, update):
if not isinstance(update, Update) and not update.effective_message: if not isinstance(update, Update) and not update.effective_message:
return False return False
if self.filters: if self.filters:
message = update.effective_message message = update.effective_message
if isinstance(self.filters, list): if isinstance(self.filters, list):
res = any(func(message) for func in self.filters) res = any(func(message) for func in self.filters)
else: else:
res = self.filters(message) res = self.filters(message)
if not res: if not res:
return False return False
if any([self.message_updates and update.message, if any([self.message_updates and update.message,
self.edited_updates and (update.edited_message or update.edited_channel_post), self.edited_updates and (update.edited_message or update.edited_channel_post),
self.channel_post_updates and update.channel_post]) and \ self.channel_post_updates and update.channel_post]) and \
update.effective_message.text: update.effective_message.text:
match = re.match(self.pattern, update.effective_message.text) match = re.match(self.pattern, update.effective_message.text)
return bool(match) return bool(match)
return False return False
\ No newline at end of file \ No newline at end of file
...@@ -11,35 +11,35 @@ from bot import strings as s ...@@ -11,35 +11,35 @@ from bot import strings as s
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
extended_help_markup = InlineKeyboardMarkup([ extended_help_markup = InlineKeyboardMarkup([
[InlineKeyboardButton("extended help", callback_data="extend")] [InlineKeyboardButton("extended help", callback_data="extend")]
]) ])
short_help_markup = InlineKeyboardMarkup([ short_help_markup = InlineKeyboardMarkup([
[InlineKeyboardButton("reduce", callback_data="reduce")] [InlineKeyboardButton("reduce", callback_data="reduce")]
]) ])
@run_async @run_async
def help_message(bot, update): def help_message(bot, update):
logger.info("/help or /start command") logger.info("/help or /start command")
update.message.reply_markdown(s.help_short, update.message.reply_markdown(s.help_short,
reply_markup=extended_help_markup, disable_web_page_preview=True) reply_markup=extended_help_markup, disable_web_page_preview=True)
@run_async @run_async
def on_extended_help_button(bot, update): def on_extended_help_button(bot, update):
logger.info("extend help") logger.info("extend help")
update.callback_query.message.edit_text(s.help_extended, update.callback_query.message.edit_text(s.help_extended,
reply_markup=short_help_markup, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) reply_markup=short_help_markup, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
@run_async @run_async
def on_short_help_button(bot, update): def on_short_help_button(bot, update):
logger.info("reduce help") logger.info("reduce help")
update.callback_query.message.edit_text(s.help_short, update.callback_query.message.edit_text(s.help_short,
reply_markup=extended_help_markup, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) reply_markup=extended_help_markup, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
class module: class module:
name = "help" name = "help"
handlers = ( handlers = (
CommandHandler(["start", "help"], help_message, filters=Filters.private), CommandHandler(["start", "help"], help_message, filters=Filters.private),
CallbackQueryHandler(on_extended_help_button, pattern='^extend$'), CallbackQueryHandler(on_extended_help_button, pattern='^extend$'),
CallbackQueryHandler(on_short_help_button, pattern='^reduce$'), CallbackQueryHandler(on_short_help_button, pattern='^reduce$'),
) )
\ No newline at end of file \ No newline at end of file
...@@ -12,55 +12,55 @@ logger = logging.getLogger(__name__) ...@@ -12,55 +12,55 @@ logger = logging.getLogger(__name__)
COMMAND_REGEX = r"^([s*]?/?)/((?:\\/|[^/])+)/((?:\\/|[^/])*)(?:/(.*))?" COMMAND_REGEX = r"^([s*]?/?)/((?:\\/|[^/])+)/((?:\\/|[^/])*)(?:/(.*))?"
MODES = { MODES = {
"": "<b>Did you mean:</b>\n{}", "": "<b>Did you mean:</b>\n{}",
"s": "{}", "s": "{}",
"*": "*{}" "*": "*{}"
} }
def get_response(mode, string): def get_response(mode, string):
mode = mode.replace("/", "") mode = mode.replace("/", "")
return MODES[mode].format(html_escape(string)) return MODES[mode].format(html_escape(string))
@run_async @run_async
def on_sed(bot, update, groups): def on_sed(bot, update, groups):
text = update.message.reply_to_message.text or update.message.reply_to_message.caption text = update.message.reply_to_message.text or update.message.reply_to_message.caption
mode = groups[0] mode = groups[0]
pattern = groups[1] pattern = groups[1]
replacement = groups[2].replace('\\/', '/') # ??? https://github.com/SijmenSchoon/regexbot/blob/master/regexbot.py#L25 replacement = groups[2].replace('\\/', '/') # ??? https://github.com/SijmenSchoon/regexbot/blob/master/regexbot.py#L25
flags = groups[3] if len(groups) > 3 else None flags = groups[3] if len(groups) > 3 else None
logger.info("\nmode: %s\ntext: %s\npattern: %s\nreplacement: %s\nflags: %s", logger.info("\nmode: %s\ntext: %s\npattern: %s\nreplacement: %s\nflags: %s",
mode, mode,
text, text,
pattern, pattern,
replacement, replacement,
flags flags
) )
regex = Regex(text, pattern, replacement, flags) regex = Regex(text, pattern, replacement, flags)
try: try:
new_string, n_subs = regex.subn() new_string, n_subs = regex.subn()
logger.info("re.subn result:\nnew_string: %s\nn_subs: %d", new_string, n_subs) logger.info("re.subn result:\nnew_string: %s\nn_subs: %d", new_string, n_subs)
except Exception as e: except Exception as e:
logger.info("re.subn exception: %s", str(e), exc_info=True) logger.info("re.subn exception: %s", str(e), exc_info=True)
#update.message.reply_text(s.oopsie_woopsie) # might be the user who fucked up the regex #update.message.reply_text(s.oopsie_woopsie) # might be the user who fucked up the regex
return # don't proceed further return # don't proceed further
if n_subs > 0: if n_subs > 0:
if len(new_string) > MAX_MESSAGE_LENGTH: if len(new_string) > MAX_MESSAGE_LENGTH:
logger.info("result too long: substringing...") logger.info("result too long: substringing...")
new_string = new_string[:MAX_MESSAGE_LENGTH-16] # -16: "*Did you mean:*\n" new_string = new_string[:MAX_MESSAGE_LENGTH-16] # -16: "*Did you mean:*\n"
update.message.reply_to_message.reply_html(get_response(mode, new_string), disable_web_page_preview=True) update.message.reply_to_message.reply_html(get_response(mode, new_string), disable_web_page_preview=True)
if mode.endswith("/"): # try to delete the command if mode.endswith("/"): # try to delete the command
try: try:
update.message.delete() update.message.delete()
except BadRequest as e: # the bot doesn't have the permission to delete the message except BadRequest as e: # the bot doesn't have the permission to delete the message
logger.info("exception while trying to delete a message: %s", e) logger.info("exception while trying to delete a message: %s", e)
class module: class module:
name = "sed" name = "sed"
handlers = ( handlers = (
FilteredRegexHandler(COMMAND_REGEX, on_sed, pass_groups=True, FilteredRegexHandler(COMMAND_REGEX, on_sed, pass_groups=True,
filters=Filters.reply_text), filters=Filters.reply_text),
) )
\ No newline at end of file \ No newline at end of file
...@@ -12,12 +12,12 @@ YESNO_REGEX = re.compile(r".*(?:y(?:es)?\/no?|no?\/y(?:es)?)$", re.I) ...@@ -12,12 +12,12 @@ YESNO_REGEX = re.compile(r".*(?:y(?:es)?\/no?|no?\/y(?:es)?)$", re.I)
@run_async @run_async
def on_yesno(bot, update): def on_yesno(bot, update):
logger.info("yes/no") logger.info("yes/no")
reply = choice(s.yesno_list) reply = choice(s.yesno_list)
update.message.reply_text(reply) update.message.reply_text(reply)
class module: class module:
name = "yesno" name = "yesno"
handlers = ( handlers = (
RegexHandler(YESNO_REGEX, on_yesno), RegexHandler(YESNO_REGEX, on_yesno),
) )
\ No newline at end of file \ No newline at end of file
...@@ -5,46 +5,46 @@ logger = logging.getLogger(__name__) ...@@ -5,46 +5,46 @@ logger = logging.getLogger(__name__)
REGEX_FLAGS = "ilmsax" REGEX_FLAGS = "ilmsax"
FLAGS_DICT = { FLAGS_DICT = {
"i": re.I, "i": re.I,
"l": re.L, "l": re.L,
"m": re.M, "m": re.M,
"s": re.S, "s": re.S,
"a": re.A, "a": re.A,
"x": re.X "x": re.X
} }
class Regex(): class Regex():
def __init__(self, string, pattern, repl, flags=None): def __init__(self, string, pattern, repl, flags=None):
self.string = string self.string = string
self.pattern = pattern self.pattern = pattern
self.repl = repl self.repl = repl
self.count = 1 # by default, make just one replacement, unless the "g" flag is passed self.count = 1 # by default, make just one replacement, unless the "g" flag is passed
self.flags = 0 # default value for the "flags" argument of re.sub/re.subn self.flags = 0 # default value for the "flags" argument of re.sub/re.subn
if flags: if flags:
for flag in flags: for flag in flags:
logger.info("elaborating flag: %s", flag) logger.info("elaborating flag: %s", flag)
flag_lower = flag.lower() flag_lower = flag.lower()
if flag_lower == "g": # re.G: don't return after the first match if flag_lower == "g": # re.G: don't return after the first match
logger.info("<g> flag found") logger.info("<g> flag found")
self.count = 0 # passing count=0 to resub/re.subn will make it not return after the first match self.count = 0 # passing count=0 to resub/re.subn will make it not return after the first match
if flag_lower in REGEX_FLAGS: if flag_lower in REGEX_FLAGS:
self.flags |= FLAGS_DICT[flag_lower] # biwise-concatenete the re.FLAG object self.flags |= FLAGS_DICT[flag_lower] # biwise-concatenete the re.FLAG object
def subn(self, escape_html=False): def subn(self, escape_html=False):
return re.subn( return re.subn(
self.pattern, self.pattern,
self.repl, self.repl,
self.string, self.string,
flags=self.flags, flags=self.flags,
count=self.count count=self.count
) )
def sub(self, escape_html=False): def sub(self, escape_html=False):
return re.sub( return re.sub(
self.pattern, self.pattern,
self.repl, self.repl,
self.string, self.string,
flags=self.flags, flags=self.flags,
count=self.count count=self.count
) )
...@@ -41,8 +41,8 @@ The code monkeys at our headquarters are working VEWY HAWD to fix this!\ ...@@ -41,8 +41,8 @@ The code monkeys at our headquarters are working VEWY HAWD to fix this!\
""" """
yesno_list = ( yesno_list = (
'Yes.', 'Yes.',
'No.', 'No.',
'Absolutely.', 'Absolutely.',
'In your dreams.' 'In your dreams.'
) )
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment