are there any APIs for changing google-talk status? - ruby

I want to write an application, which will:
recieve and send email messages ( I know, I can do it with
ActionMailer using RoR )
chat with my Google+ friends
change my GoogleTalk (gmail) status
So, when I open my gmail interface, I see list with my contacts on the left side of page. I can open chat with people from this list, I can change status and name (near my little google+ avatar).
Is exists some Google API for changing google-talk status (special message)? Can I do it using some RubyOnRails gems?
Thanks.

So, this pretty lines of ruby code ( using xmpp4r gem ),
change your google_talk status and send chat_message to your friend.
Thank you, #Arkan!
require 'xmpp4r'
# init jabber client
client_jid = Jabber::JID.new( 'your_email#gmail.com' )
client = Jabber::Client.new( client_jid )
client.connect 'talk.google.com'
client.auth 'your_gmail_password'
# change google_talk status
client.send( Jabber::Presence.new.set_show( :chat ).set_status( 'Your New GoogleTalk status' ) )
# send chat_message to friend
friend = Jabber::JID.new("your_friend_email#gmail.com")
message = Jabber::Message::new(friend, "it's chat message").set_type(:normal).set_id('1')
client.send(message)
I love ruby ^_^ !

Xmpp Implementation of Gtalk. To change status This might help you.
import xmpp
import dns
class Gtalk():
def __init__(self,bot_id,bot_pwd):
self.bot_id = bot_id
self.bot_pwd = bot_pwd
def connect(self):
self.jid = xmpp.protocol.JID(self.bot_id)
self.presnc = xmpp.protocol.Presence()
self.conn = xmpp.Client(self.jid.getDomain(),debug=[])
if self.conn.connect():
print 'connected..'
self.auth()
else:
print 'err to connect'
def auth(self):
if self.conn.auth(self.jid.getNode(),self.bot_pwd):
self.conn.sendInitPresence()
print 'Authenticated..'
else:
print 'err to authenticate'
def setStatus(self,value):
self.conn.send(xmpp.protocol.Presence(status=value))
def invisible(self,username):
self.conn.send(xmpp.protocol.Presence(username,typ='unavailable'))
def visible(slef,username):
self.conn.send(xmpp.protocol.Presence(username,typ=None))
def disconnect(self):
self.conn.disconnect()

Related

How to make my telegram-bot multi-threading?

I have a trouble. I need make my telegram-bot multi-threading. My bot will help users to buy films and will work with database. I use Webhooks-method for receiving requests from Telegram-server and Stripe(module request). I read a lot about threading module in python and about async functions but I am not sure for all 100% about how to make my bot multi-threading. I will very appreciated for help, because I am stuck on this question.
For now I give you main function of my app, if you need more, tell me:
#app.route('/', methods=["POST"])
def process():
print(request.json) # receiving requests (messages) in json format that are sent to the Flask server from the Telegram server and Stripe
if check_if_successful_payment(request) == True:
# Processing a request from Stripe
# chat_id = request.json["data"]["object"]["metadata"]["chat_id"]
stripe.api_key = get_from_env("PAYMENT_TOKEN")
webhook_list = stripe.WebhookEndpoint.list()
chat_id = webhook_list.data[0].metadata.chat_id
send_message(chat_id, "The payment was successful! Enjoy watching the movie!")
print("The payment was successful!")
webhook_id = webhook_list.data[0].id
stripe.WebhookEndpoint.delete(
webhook_id,
)
else:
# Processing a request from Telegram
chat_id = request.json["message"]["chat"]["id"]
send_message(chat_id, check_message(chat_id, request.json["message"]["text"]))
send_pay_button(chat_id=chat_id, text="Test payment",
price_id=check_price_id(request.json["message"]["text"]))
return {"ok": True}
if __name__ == '__main__':
app.run(debug=True)
If your bot works on Webhooks, you can use Aiogram instead of Flask for receiving messages from users. Aiogram has special decorator for simultaneous messages processing from many users - async_task: https://docs.aiogram.dev/en/latest/_modules/aiogram/dispatcher/dispatcher.html#Dispatcher.async_task

How to rig a bot's command to only a certain user

I've been making this pp size machine, which is somewhat like dank memer's one
#client.command()
async def pp(ctx,member : discord.Member):
size=random.randint(1,10)
message = "8"
for x in range (size):
message= message + "="
if x == size-1:
message = message + "D"
if member == "PROTATO#6826":
message = "8D"
ppsize = discord.Embed(color=discord.Colour.orange(), title=f"PP size",description=f"""{member}'s penis
{message} """)
await ctx.send(embed = ppsize)
But i want to rig the command for a certain user to only show "8D" instead of the random lengths.
But no matter what it is the
if member == "PROTATO#6826":
message = "8D"
code doesnt run or gets over looked?
Can someone help me out with this?
You can check if the member mentioned has the same id as a specific user. You can either enable developer mode on discord, or you can print the member.id at the very beginning. Do view a code example below.
#client.command()
async def pp(ctx, member: discord.Member):
print(member.id) # this would print a user's unique id
message = "Hey!"
if member.id == 394506589350002688: # replace this id with what was printed at the start
message = "Hello!"
await ctx.send(message)
Similar Questions:
How to check if message was sent by certain user? - SO
How do I detect if the message is sent by a specific user id? - SO

How can I send messages to specific client using Faye Websockets?

I've been working on a web application which is essentially a web messenger using sinatra. My goal is to have all messages encrypted using pgp and to have full duplex communication between clients using faye websocket.
My main problem is being able to send messages to a specific client using faye. To add to this all my messages in a single chatroom are saved twice for each person since it is pgp encrypted.
So far I've thought of starting up a new socket object for every client and storing them in a hash. I do not know if this approach is the most efficient one. I have seen that socket.io for example allows you to emit to a specific client but not with faye websockets it seems ? I am also considering maybe using a pub sub model but once again I am not sure.
Any advice is appreciated thanks !
I am iodine's author, so I might be biased in my approach.
I would consider naming a channel by the used ID (i.e. user1...user201983 and sending the message to the user's channel.
I think Faye will support this. I know that when using the iodine native websockets and builtin pub/sub, this is quite effective.
So far I've thought of starting up a new socket object for every client and storing them in a hash...
This is a very common mistake, often seen in simple examples.
It works only in single process environments and than you will have to recode the whole logic in order to scale your application.
The channel approach allows you to scale using Redis or any other Pub/Sub service without recoding your application's logic.
Here's a quick example you can run from the Ruby terminal (irb). I'm using plezi.io just to make it a bit shorter to code:
require 'plezi'
class Example
def index
"Use Websockets to connect."
end
def pre_connect
if(!params[:id])
puts "an attempt to connect without credentials was made."
return false
end
return true
end
def on_open
subscribe channel: params[:id]
end
def on_message data
begin
msg = JSON.parse(data)
if(!msg["to"] || !msg["data"])
puts "JSON message error", data
return
end
msg["from"] = params[:id]
publish channel: msg["to"].to_s, message: msg.to_json
rescue => e
puts "JSON parsing failed!", e.message
end
end
end
Plezi.route "/" ,Example
Iodine.threads = 1
exit
To test this example, use a Javascript client, maybe something like this:
// in browser tab 1
var id = 1
ws = new WebSocket("ws://localhost:3000/" + id)
ws.onopen = function(e) {console.log("opened connection");}
ws.onclose = function(e) {console.log("closed connection");}
ws.onmessage = function(e) {console.log(e.data);}
ws.send_to = function(to, data) {
this.send(JSON.stringify({to: to, data: data}));
}.bind(ws);
// in browser tab 2
var id = 2
ws = new WebSocket("ws://localhost:3000/" + id)
ws.onopen = function(e) {console.log("opened connection");}
ws.onclose = function(e) {console.log("closed connection");}
ws.onmessage = function(e) {console.log(e.data);}
ws.send_to = function(to, data) {
this.send(JSON.stringify({to: to, data: data}));
}.bind(ws);
ws.send_to(1, "hello!")

Can't send a message from xmpp4r?

I'm trying to test sending a message to one jid account by using xmpp4r:
require 'xmpp4r'
include Jabber
jid = JID::new('alice#wonderland.lit')
password = 'secr3t'
cl = Client::new(jid)
cl.connect('166.78.7.179')
cl.auth(password)
cl.send(Presence.new)
to = 'arthur#wonderland.lit'
subject = 'XMPP4R test'
body = 'Hi, this is a XMPP4R test'
m = Message::new( to, body ).set_type(:chat).set_id('1').set_subject(subject)
cl.send m
But I always get the following exception:
/home/subout/.rvm/gems/ruby-1.9.3-p374#subout/gems/xmpp4r-0.5/lib/xmpp4r/client.rb:118:in `rescue in auth': closed stream (Jabber::ClientAuthenticationFailure)
from /home/subout/.rvm/gems/ruby-1.9.3-p374#subout/gems/xmpp4r-0.5/lib/xmpp4r/client.rb:108:in `auth'
from send_message2.rb:9:in `<main>'
First of all, would you please add Jabber::debug = true setting
before cl.connect and post output here?
Secondly, it looks like there is a problem with XMPP server (are you sure it’s running at
'166.78.7.179'?)
And, the last but not the least, why do you decide
to use “obsolete” xmpp4r rather than it’s modern successor
Blather?

Connecting to Yahoo! mail from Ruby

I try to connect to mail Yahoo! account from Ruby using both net/imap and net/pop. But I randomly get error EOFile (from IMAP) or Connection Refused/Reset by peer (from POP). Has anybody tried to connect to Yahoo! Mail and had some experiences about it?
There's a bug in ruby's net/imap library that is exposed when connecting to Yahoo.
The fix is straightforward and described here:
http://redmine.ruby-lang.org/issues/4509
Basically, edit imap.rb and change the inner loop of search_response method from:
token = lookahead
case token.symbol
when T_CRLF
break
when T_SPACE
shift_token
end
data.push(number)
to:
token = lookahead
case token.symbol
when T_CRLF
break
when T_SPACE
shift_token
else
data.push(number)
end
then test with the following code:
require 'net/imap'
Net::IMAP.debug = true
conn = Net::IMAP.new('imap.mail.yahoo.com', 143, false)
conn.instance_eval { send_command('ID ("GUID" "1")') }
conn.authenticate('LOGIN', ARGV[0], ARGV[1] )
conn.select("INBOX")
uids = conn.uid_search(['ALL'])
puts uids.join(',')
conn.logout
conn.disconnect

Resources