Don't split words

This commit is contained in:
ekardnam 2019-07-24 07:49:56 +02:00
parent a314ce0496
commit 6e0a8961e6

61
main.js
View file

@ -24,46 +24,37 @@ let mastodon = new Mastodon({
let lastPostDate = new Date().getTime()
// splits a tweet into pieces that are less than TWITTER_MAX_CHARS long
function splitTweet(post, pieces = []) {
if (post.length > TWITTER_MAX_CHARS) {
let index = TWITTER_MAX_CHARS - 3 // 3 for appending ...
while (post.charAt(index) !== ' ' && index > 0) index--
if (index === 0) {
/*if a word if longer than TWITTER_MAX_CHARS-3 split the word*/
index = TWITTER_MAX_CHARS - 3
}
return splitTweet(post.substring(index+1), pieces.concat([post.substring(0, index) + '...']))
}
return pieces.concat([post])
}
// post to twitter
// if post is longer than TWITTER_MAX_CHARS divides in multiple tweets
function twitterPost(post, originalSource) {
function recursivePost(post, inReplyTo = null, tweetCount = 0, fullPost = '') {
if (inReplyTo) {
if (post.length < TWITTER_MAX_CHARS) {
twitter.post('statuses/update', { status: post, in_reply_to_status_id: inReplyTo }, (err, data, response) => {
if (tweetCount > 0) console.log(`[INFO] Partial tweet #${tweetCount}`)
console.log(`[INFO] Tweeted ${fullPost}`)
if (err) console.error(err)
// exit recursion
})
let replyTo = null
let success = true
splitTweet(post).forEach((piece, i) => {
twitter.post('statuses/update', { status: piece, in_reply_to_status_id: replyTo }, (err, data, response) => {
if (err) {
success = false
console.error(err)
} else {
twitter.post('statuses/update', { status: post.substring(0, TWITTER_MAX_CHARS-3) + '...', in_reply_to_status_id: inReplyTo }, (err, data, response) => {
console.log(`[INFO] Partial tweet #${tweetCount}`)
if (err) console.error(err)
recursivePost(post.substring(TWITTER_MAX_CHARS-3), data.id_str, tweetCount + 1, fullPost)
})
replyTo = data.id_str
}
} else {
if (post.length < TWITTER_MAX_CHARS) {
twitter.post('statuses/update', { status: post }, (err, data, response) => {
console.log(`[INFO] Tweeted ${post}`)
if (err) console.error(err)
})
})
// exit recursion
})
} else {
twitter.post('statuses/update', { status: post.substring(0, TWITTER_MAX_CHARS-3) + '...' }, (err, data, response) => {
console.log(`[INFO] Partial tweet #${tweetCount}`)
if (err) console.error(err)
recursivePost(post.substring(TWITTER_MAX_CHARS-3), data.id_str, tweetCount + 1, post)
})
}
}
}
recursivePost(post)
if (success) console.log(`[INFO] Tweeted ${post}`)
}
// makes a post formatted for twitter
@ -71,7 +62,7 @@ function twitterPost(post, originalSource) {
function twitterFormat(post) {
post = post.replace('<br/>', '\n') // new lines
post = post.replace('<p>', '')
post = post.replace('<p/>', '')
post = post.replace('</p>', '\n')
return post
}