Removed twitter module

This commit is contained in:
Erik C. Thauvin 2023-05-21 00:01:01 -07:00
parent c2c5f8beae
commit 207c1b7e02
29 changed files with 360 additions and 416 deletions

View file

@ -59,6 +59,12 @@ object Constants {
*/
const val CLI_CMD = "java -jar ${ReleaseInfo.PROJECT}.jar"
/**
* User-Agent
*/
const val USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
/**
* The help command.
*/

View file

@ -74,7 +74,7 @@ class FeedReader(private val url: String, val event: GenericMessageEvent) : Runn
fun readFeed(url: String, maxItems: Int = 5): List<Message> {
val messages = mutableListOf<Message>()
val input = SyndFeedInput()
XmlReader(URL(url)).use { reader ->
XmlReader(URL(url).openStream()).use { reader ->
val feed = input.build(reader)
val items = feed.entries
if (items.isEmpty()) {

View file

@ -78,7 +78,6 @@ import net.thauvin.erik.mobibot.modules.Mastodon
import net.thauvin.erik.mobibot.modules.Ping
import net.thauvin.erik.mobibot.modules.RockPaperScissors
import net.thauvin.erik.mobibot.modules.StockQuote
import net.thauvin.erik.mobibot.modules.Twitter
import net.thauvin.erik.mobibot.modules.War
import net.thauvin.erik.mobibot.modules.Weather2
import net.thauvin.erik.mobibot.modules.WolframAlpha
@ -438,7 +437,7 @@ class Mobibot(nickname: String, val channel: String, logsDirPath: String, p: Pro
addons.add(View())
// Load social modules
LinksManager.socialManager.add(addons, Twitter(), Mastodon())
LinksManager.socialManager.add(addons, Mastodon())
// Load the modules
addons.add(Calc())

View file

@ -1,118 +0,0 @@
/*
* TwitterOAuth.kt
*
* Copyright 2004-2023 Erik C. Thauvin (erik@thauvin.net)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of this project nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.thauvin.erik.mobibot
import twitter4j.AccessToken
import twitter4j.OAuthAuthorization
import twitter4j.TwitterException
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import kotlin.system.exitProcess
/**
* The `TwitterOAuth` class.
*
* Go to [https://developer.twitter.com/en/apps](https://developer.twitter.com/en/apps) to register your bot.
*
* Then execute:
*
* `java -cp mobibot.jar net.thauvin.erik.mobibot.TwitterOAuth <consumerKey> <consumerSecret>`
*
* and follow the prompts/instructions.
*
* @author [Erik C. Thauvin](https://erik.thauvin.net)
* @author [Yusuke Yamamoto](https://github.com/Twitter4J/Twitter4J/blob/main/twitter4j-examples/src/main/java/examples/oauth/GetAccessToken.java)
*/
object TwitterOAuth {
/**
* Twitter OAuth Client Registration.
*
* @param args The consumerKey and consumerSecret should be passed as arguments.
*/
@JvmStatic
fun main(args: Array<String>) {
if (args.size == 2) {
try {
val oAuthAuthorization = OAuthAuthorization.getInstance(args[0], args[1])
val requestToken = oAuthAuthorization.oAuthRequestToken
var accessToken: AccessToken? = null
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()) {
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>")
}
exitProcess(0)
}
}

View file

@ -31,6 +31,7 @@
package net.thauvin.erik.mobibot.modules
import net.thauvin.erik.mobibot.Constants
import net.thauvin.erik.mobibot.Utils
import net.thauvin.erik.mobibot.Utils.sendMessage
import org.apache.commons.text.WordUtils
@ -106,6 +107,7 @@ class ChatGpt : AbstractModule() {
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer $apiKey")
.header("User-Agent", Constants.USER_AGENT)
.POST(
HttpRequest.BodyPublishers.ofString(
"""{
@ -136,8 +138,10 @@ class ChatGpt : AbstractModule() {
}
} else {
if (response.statusCode() == 429) {
throw ModuleException("$CHATGPT_CMD($query): Rate limit reached",
"Rate limit reached. Please try again later.")
throw ModuleException(
"$CHATGPT_CMD($query): Rate limit reached",
"Rate limit reached. Please try again later."
)
} else {
throw IOException("HTTP Status Code: " + response.statusCode())
}

View file

@ -1,133 +0,0 @@
/*
* Twitter.kt
*
* Copyright 2004-2023 Erik C. Thauvin (erik@thauvin.net)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of this project nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.thauvin.erik.mobibot.modules
import net.thauvin.erik.mobibot.Utils.helpFormat
import net.thauvin.erik.mobibot.entries.EntryLink
import net.thauvin.erik.mobibot.social.SocialModule
import twitter4j.TwitterException
/**
* The Twitter module.
*/
class Twitter : SocialModule() {
override val name = "Twitter"
override val handle: String?
get() = properties[HANDLE_PROP]
override val isAutoPost: Boolean
get() = isEnabled && properties[AUTO_POST_PROP].toBoolean()
override val isValidProperties: Boolean
get() = !(properties[CONSUMER_KEY_PROP].isNullOrBlank() || properties[CONSUMER_SECRET_PROP].isNullOrBlank()
|| properties[TOKEN_PROP].isNullOrBlank() || properties[TOKEN_SECRET_PROP].isNullOrBlank())
/**
* Formats the entry for posting.
*/
override fun formatEntry(entry: EntryLink): String {
return "${entry.title} ${entry.link} via ${entry.nick} on ${entry.channel}"
}
/**
* Posts on Twitter.
*/
@Throws(ModuleException::class)
override fun post(message: String, isDm: Boolean): String {
return tweet(
consumerKey = properties[CONSUMER_KEY_PROP],
consumerSecret = properties[CONSUMER_SECRET_PROP],
token = properties[TOKEN_PROP],
tokenSecret = properties[TOKEN_SECRET_PROP],
handle = handle,
message = message,
isDm = isDm
)
}
companion object {
// Property keys
const val AUTO_POST_PROP = "twitter-auto-post"
const val CONSUMER_KEY_PROP = "twitter-consumerKey"
const val CONSUMER_SECRET_PROP = "twitter-consumerSecret"
const val HANDLE_PROP = "twitter-handle"
const val TOKEN_PROP = "twitter-token"
const val TOKEN_SECRET_PROP = "twitter-tokenSecret"
// Twitter commands
private const val TWITTER_CMD = "twitter"
private const val TWEET_CMD = "tweet"
/**
* Post on Twitter.
*/
@JvmStatic
@Throws(ModuleException::class)
fun tweet(
consumerKey: String?,
consumerSecret: String?,
token: String?,
tokenSecret: String?,
handle: String?,
message: String,
isDm: Boolean
): String {
return try {
val twitter = twitter4j.Twitter.newBuilder()
.prettyDebugEnabled(true)
.oAuthConsumer(consumerKey, consumerSecret)
.oAuthAccessToken(token, tokenSecret)
.build()
if (!isDm) {
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.v1().directMessages().sendDirectMessage(handle, message)
dm.text
}
} catch (e: TwitterException) {
throw ModuleException("tweet($message)", "An error has occurred: ${e.message}", e)
}
}
}
init {
commands.add(TWITTER_CMD)
commands.add(TWEET_CMD)
help.add("To $TWEET_CMD on $name:")
help.add(helpFormat("%c $TWEET_CMD <message>"))
properties[AUTO_POST_PROP] = "false"
initProperties(CONSUMER_KEY_PROP, CONSUMER_SECRET_PROP, HANDLE_PROP, TOKEN_PROP, TOKEN_SECRET_PROP)
}
}