forked from franciscod/telegram-twitter-forwarder-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
46 lines (34 loc) · 1.36 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from functools import wraps
import re
def with_touched_chat(f):
@wraps(f)
def wrapper(bot, update=None, *args, **kwargs):
if update is None:
return f(bot, *args, **kwargs)
chat = bot.get_chat(update.message.chat)
chat.touch_contact()
kwargs.update(chat=chat)
return f(bot, update, *args, **kwargs)
return wrapper
def escape_markdown(text):
"""Helper function to escape telegram markup symbols"""
escape_chars = '\*_`\['
return re.sub(r'([%s])' % escape_chars, r'\\\1', text)
def markdown_twitter_usernames(text):
"""Restore markdown escaped usernames and make them link to twitter"""
return re.sub(r'@([A-Za-z0-9_\\]+)',
lambda s: '[@{username}](https://twitter.com/{username})'
.format(username=s.group(1).replace(r'\_', '_')),
text)
def markdown_twitter_hashtags(text):
"""Restore markdown escaped hashtags and make them link to twitter"""
return re.sub(r'#([^\s]*)',
lambda s: '[#{tag}](https://twitter.com/hashtag/{tag})'
.format(tag=s.group(1).replace(r'\_', '_')),
text)
def prepare_tweet_text(text):
"""Do all escape things for tweet text"""
res = escape_markdown(text)
res = markdown_twitter_usernames(res)
res = markdown_twitter_hashtags(res)
return res