LoginSignup
4
4

More than 5 years have passed since last update.

[Ruby] XMPP のグループチャットにテキストファイルの内容を投稿する

Posted at

定期的に XMPP で特定のメッセージを特定のグループチャットに送信する必要があったので作成。これでさぼっていても仕事をしているように見せかけることが

仕様

  • とあるディレクトリにあるテキストファイルの内容を、とあるグループチャットに投稿する
xmpp_bot.rb
require 'xmpp4r'
require 'xmpp4r/muc'

# メッセージが書いてあるテキスト置き場
text_file = '/ika/geso.txt'

# xmpp ログイン情報
jid = 'ika'
password = 'geso'

# グループチャット名など
bot_name = 'ika_bot'
group_chat_room_name = 'ika@conference.geso'

# xmpp サーバにログインする
def xmpp_login(jid, password)
    client = Jabber::Client.new(Jabber::JID.new(jid))
    client.connect
    client.auth(password)
    return client
end

# グループチャット部屋に入る
def group_chat_login(client, group_chat_room_name, bot_name)
    muc = Jabber::MUC::MUCClient.new(client)
    muc.join("#{group_chat_room_name}/#{bot_name}")
    return muc
end

# グループチャット部屋にメッセージを送信する
def send_group_chat_message(group_chat, group_chat_room_name, message_string)
    message = Jabber::Message.new(group_chat_room_name, message_string)
    group_chat.send(message)
end

# メイン処理
message_string = File.read(text_file, encoding: 'utf-8')
client = xmpp_login(jid, password)
group_chat = group_chat_login(client, group_chat_room_name, bot_name)
message_string = File.read(text_file, encoding: 'utf-8')
send_group_chat_message(group_chat, group_chat_room_name, message_string)

# 後始末
group_chat.exit
client.close

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4