如何用ruby写自动按赞的脚本
cn·@tensaix2j·
0.000 HBD如何用ruby写自动按赞的脚本

发现这里很多Python的教材,却很少Ruby 的教材,但本人又是比较常写Ruby 脚本的程序员, 所以就写了一个。
要用Ruby 在Steemit 帮忙自动在适当的时间按赞,可以用 @inertia 开发的 radiator 库
https://github.com/inertia186/radiator
以下来讲解大概如何使用radiator 写一个简单的自动按赞脚本。
```
require 'radiator'
```
---
首先,需要instantiate 一个 stream 的object
```
stream = Radiator::Stream.new
```
因为要setup 一个stream operation 的event loop 如下
```
stream.operations(:comment) do |op|
end
```
那么有新帖子就会进入上面那个block, op 的properties里会有包含作者,时间,标题,等等的讯息。
---
接下来,我们要检查 op["parent_author"] 是否是空, 因为不要vote comment,
如果不是comment,我们再检查作者 op["author"] 是否是我们要vote 的对象。
遇到可以vote的帖子后,
先不要急着vote, 因为我们要等帖子至少要 25分钟的熟度,不然作者拿完 (但又不可以太迟,因为会被别人抢先 ), 所以牺牲5分钟无所谓。
我们先把帖子塞进一个queue 里, 待会而在 process_votequeue 时检查queue的头是否到钟vote 了。
```
if op["parent_author"] == "" && @popular_fellows.index(op["author"]) != nil
votable = {}
votable[:author] = op["author"]
votable[:permlink] = op["permlink"]
# To vote after 25 minutes
votable[:votetime] = Time.now.to_i + 25 * 60
@vote_queue << votable
puts "#{ Time.now().strftime("%Y%m%d.%H%M%S") } (#{ Time.now.to_i }) : Queued : #{ votable.inspect }"
end
process_votequeue(api)
```
---
然后我们的 process_votequeue 如下, 基本上每次只需要检查queue 的头是否到钟了。 如果到钟就vote ,还没到就什么都别做。
如果有做什么, 就把做掉的element 从 queue 里 shift 掉
```
def process_votequeue( api )
if @vote_queue.length > 0
votable = @vote_queue[0]
if Time.now.to_i >= votable[:votetime]
@voters.each { |v|
vote( votable[:author], v["user"], v["wif"], votable[:permlink] )
sleep 3
}
@vote_queue.shift
end
end
end
```
---
然后我们的 vote 的函数如下。 这个函数是可以独立使用的。
```
def vote( author, voter, voter_wif , permlink )
puts "#{voter} to vote for #{author}"
begin
tx = Radiator::Transaction.new(wif: voter_wif)
vote = {
type: :vote,
voter: voter,
author: author,
permlink: permlink,
weight: 10000
}
tx.operations << vote
tx.process(true)
rescue Exception => ex
puts "\n Failed to vote for #{author}. Error #{ex.to_s}"
end
end
```
---
接下来要写一个 config file 放们所有要用到账号的wif 。所以准备一个config.json 如下。 把user01 和 wif 改成你自己的,
还有popular_fellows 改成你想vote 的对象。
```
{
"voters":[
{
"user":"user01",
"wif":"wif"
},
{
"user":"user02",
"wif":"wif02"
}
],
"popular_fellows": [
"sweetsssj",
"stan",
"dollarvigilante",
"ats-david",
"kingscrown",
"jerrybanfield"
]
}
```
---
在写一个简单读取config 的函数
```
def populate_voters
@voters = []
@popular_fellows = []
begin
config = JSON.parse( open("config.json").read() )
@voters = config["voters"]
@popular_fellows = config["popular_fellows"]
rescue Exception => ex
puts ex.to_s
end
end
```
完成了。 完整的代码可以在我的github 找到
https://github.com/tensaix2j/steemit_star_bot
---
要跑的话, 用
```
ruby vote_popular_fellow.rb
```
就可以了。 要放在background 可以用 nohup。