Upgraded to Twitter4J 4.1

This commit is contained in:
Erik C. Thauvin 2022-10-12 20:04:29 -07:00
parent c24fcb8ef5
commit c4cf7b10d5
7 changed files with 70 additions and 60 deletions

View file

@ -31,14 +31,15 @@
*/
package net.thauvin.erik.mobibot
import twitter4j.AccessToken
import twitter4j.OAuthAuthorization
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.auth.AccessToken
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import kotlin.system.exitProcess
/**
* The `TwitterOAuth` class.
*
@ -51,7 +52,7 @@ import kotlin.system.exitProcess
* and follow the prompts/instructions.
*
* @author [Erik C. Thauvin](https://erik.thauvin.net)
* @author [Twitter4J Example](https://twitter4j.org/en/code-examples.html#oauth)
* @author [Yusuke Yamamoto](https://github.com/Twitter4J/Twitter4J/blob/main/twitter4j-examples/src/main/java/examples/oauth/GetAccessToken.java)
*/
object TwitterOAuth {
/**
@ -60,49 +61,55 @@ object TwitterOAuth {
* @param args The consumerKey and consumerSecret should be passed as arguments.
*/
@JvmStatic
@Throws(TwitterException::class, IOException::class)
fun main(args: Array<String>) {
if (args.size == 2) {
with(TwitterFactory.getSingleton()) {
setOAuthConsumer(args[0], args[1])
val requestToken = oAuthRequestToken
try {
val oAuthAuthorization = OAuthAuthorization.getInstance(args[0], args[1])
val requestToken = oAuthAuthorization.oAuthRequestToken
var accessToken: AccessToken? = null
BufferedReader(InputStreamReader(System.`in`)).use { br ->
while (null == accessToken) {
print(
"""
Open the following URL and grant access to your account:
${requestToken.authorizationURL}
val br = BufferedReader(InputStreamReader(System.`in`))
while (null == accessToken) {
print(
"""
Open the following URL and grant access to your account:
${requestToken.authorizationURL}
Enter the PIN (if available) or just hit enter. [PIN]: """.trimIndent()
)
val pin = br.readLine()
try {
accessToken = if (!pin.isNullOrEmpty()) {
getOAuthAccessToken(requestToken, pin)
} else {
oAuthAccessToken
}
println(
"""
Please add the following to the bot's property file:
twitter-consumerKey=${args[0]}
twitter-consumerSecret=${args[1]}
twitter-token=${accessToken?.token}
twitter-tokenSecret=${accessToken?.tokenSecret}
""".trimIndent()
)
} catch (te: TwitterException) {
if (401 == te.statusCode) {
println("Unable to get the access token.")
} else {
te.printStackTrace()
}
Enter the PIN (if available) or just hit enter. [PIN]: """.trimIndent()
)
val pin = br.readLine()
try {
accessToken = if (!pin.isNullOrEmpty()) {
oAuthAuthorization.getOAuthAccessToken(requestToken, pin)
} else {
oAuthAuthorization.getOAuthAccessToken(requestToken)
}
} catch (te: TwitterException) {
if (401 == te.statusCode) {
println("Unable to get the access token.")
} else {
te.printStackTrace()
}
}
}
println(
"""
Please add the following to the bot's property file:
twitter-consumerKey=${args[0]}
twitter-consumerSecret=${args[1]}
twitter-token=${accessToken.token}
twitter-tokenSecret=${accessToken.tokenSecret}
""".trimIndent()
)
} catch (te: TwitterException) {
te.printStackTrace()
println("Failed to get accessToken: " + te.message)
exitProcess(-1)
} catch (ioe: IOException) {
ioe.printStackTrace()
println("Failed to read the system input.")
exitProcess(-1)
}
} else {
println("Usage: ${TwitterOAuth::class.java.name} <consumerKey> <consumerSecret>")

View file

@ -33,9 +33,9 @@ package net.thauvin.erik.mobibot.modules
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.thauvin.erik.jokeapi.JokeApi.Companion.getJoke
import net.thauvin.erik.jokeapi.exceptions.HttpErrorException
import net.thauvin.erik.jokeapi.exceptions.JokeException
import net.thauvin.erik.jokeapi.getJoke
import net.thauvin.erik.jokeapi.models.Type
import net.thauvin.erik.mobibot.Utils.bot
import net.thauvin.erik.mobibot.Utils.colorize
@ -93,7 +93,7 @@ class Joke : ThreadedModule() {
fun randomJoke(): List<Message> {
return try {
val messages = mutableListOf<Message>()
val joke = getJoke(safe = true, type = Type.SINGLE)
val joke = getJoke(safe = true, type = Type.SINGLE, splitNewLine = true)
joke.joke.forEach {
messages.add(PublicMessage(it, Colors.CYAN))
}

View file

@ -42,8 +42,6 @@ import org.pircbotx.hooks.types.GenericMessageEvent
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.conf.ConfigurationBuilder
import java.util.Timer
/**
@ -214,20 +212,18 @@ class Twitter : ThreadedModule() {
isDm: Boolean
): String {
return try {
val cb = ConfigurationBuilder().apply {
setDebugEnabled(true)
setOAuthConsumerKey(consumerKey)
setOAuthConsumerSecret(consumerSecret)
setOAuthAccessToken(token)
setOAuthAccessTokenSecret(tokenSecret)
}
val tf = TwitterFactory(cb.build())
val twitter = tf.instance
val twitter = twitter4j.Twitter.newBuilder()
.prettyDebugEnabled(true)
.oAuthConsumer(consumerKey, consumerSecret)
.oAuthAccessToken(token, tokenSecret)
.build()
if (!isDm) {
val status = twitter.updateStatus(message)
"Your message was posted to https://twitter.com/${twitter.screenName}/statuses/${status.id}"
val status = twitter.v1().tweets().updateStatus(message)
"Your message was posted to https://twitter.com/${
twitter.v1().users().accountSettings.screenName
}/statuses/${status.id}"
} else {
val dm = twitter.sendDirectMessage(handle, message)
val dm = twitter.v1().directMessages().sendDirectMessage(handle, message)
dm.text
}
} catch (e: TwitterException) {

View file

@ -33,11 +33,14 @@ package net.thauvin.erik.mobibot.modules
import assertk.all
import assertk.assertThat
import assertk.assertions.doesNotContain
import assertk.assertions.each
import assertk.assertions.isGreaterThan
import assertk.assertions.isInstanceOf
import assertk.assertions.prop
import assertk.assertions.size
import net.thauvin.erik.mobibot.modules.Joke.Companion.randomJoke
import net.thauvin.erik.mobibot.msg.Message
import net.thauvin.erik.mobibot.msg.PublicMessage
import org.testng.annotations.Test
@ -53,6 +56,7 @@ class JokeTest {
size().isGreaterThan(0)
each {
it.isInstanceOf(PublicMessage::class.java)
it.prop(Message::msg).doesNotContain("\n")
}
}
}