properly split text for tweets and toots

pull/23/head
Mallory Hancock 2017-11-09 13:57:25 -08:00
parent 1b4f342119
commit d3f6fc4e86
1 changed files with 41 additions and 31 deletions

View File

@ -1,3 +1,5 @@
import re
from mastodon import Mastodon from mastodon import Mastodon
import tweepy import tweepy
@ -14,41 +16,49 @@ tw_auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CO
tw_auth.set_access_token(settings.TWITTER_TOKEN, settings.TWITTER_TOKEN_SECRET) tw_auth.set_access_token(settings.TWITTER_TOKEN, settings.TWITTER_TOKEN_SECRET)
twitter = tweepy.API(tw_auth) twitter = tweepy.API(tw_auth)
def post_to_mastodon(qs): def split_posts_by_length(text, length):
pattern = '.{,%d}(?:\s|$)' % length - 1
chunks = re.findall(pattern, text)
posts = [] posts = []
if len(qs) > 1: post = ''
welcome = 'Welcome new user ' for chunk in chunks:
else: if len(post + chunk) <= length:
welcome = 'Welcome new users!!!\n\n' post += chunk
message = welcome
for townie in qs:
if len(message + townie.username) + 1 > 500:
posts.append(message.strip())
message = welcome + '~{}\n'.format(townie.username)
else: else:
message += '~{}\n'.format(townie.username) posts.append(post)
posts.append(message.strip()) post = chunk
for post in posts: return posts
mastodon.post(post)
def post_to_twitter(qs):
posts = [] def post_to_mastodon(message):
if len(qs) > 1: posts = split_posts_by_length(message, 500)
welcome = 'Welcome new user ' status_info = None
else: for post in posts:
welcome = 'Welcome new users!!!\n\n' if status_info:
message = welcome status_info = mastodon.status_post(post, in_reply_to_id=status_info['id'])
for townie in qs:
if len(message + townie.username) + 1 > 140:
posts.append(message.strip())
message = welcome + '~{}\n'.format(townie.username)
else: else:
message += '~{}\n'.format(townie.username) status_info = mastodon.status_post(post)
posts.append(message.strip())
def post_to_twitter(message):
posts = split_posts_by_length(message, 140)
status_info = None
for post in posts: for post in posts:
twitter.update_status(post) if status_info:
status_info = twitter.update_status(post, in_reply_to_status_id=status_info.id)
else:
status_info = twitter.update_status(post)
def post_to_social(qs):
post_to_twitter(qs) def post_users_to_social(qs):
post_to_mastodon(qs) users = ''
for townie in qs:
users += '~{}\n'.format(townie.username)
users = users.strip()
if len(qs) > 1:
message = 'Welcome new users!!!\n\n{}'.format(users)
else:
message = 'Welcome new user {}!'.format(users)
post_to_mastodon(message)
post_to_twitter(message)