新浪微博自动推送美图

这是一个通过Sae的服务和微博的API实现的 微博自动推送美图 应用。

[如何新建一个应用]
先去微博的开放平台[https://open.weibo.com/]创建一个“网页应用”,在管理中心加入应用的管理页。

点击左侧的“应用信息”,再进入“高级信息”。

然后在“授权回调页”的地址上加上“https://你的应用名称.sinaapp.com/key.php

下面是代码:

Config.php 配置文件

<?php
header('Content-Type: text/html; charset=UTF-8');

$mysql = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
mysql_query('use 数据库名称');
mysql_query('set names utf8');

$storage = 'storage名称';
$copy = ' 本图片来自 美图推送';

function images_type($type){
    switch($type){
        case 'image/jpg':
            return 'jpg';
            break;
        case 'image/jpeg':
            return 'jpg';
            break;
        case 'image/png':
            return 'png';
            break;
        /*case 'image/gif':
            return 'gif';
            break;*/
    }
}

define('APP_Key', '应用的APP_Key');
define('APP_Secret', '应用的APP_Secret');
define('Call_Back', '应用的授权回调地址');
define('IMAGE_WIDTH', 280);//图片最小的宽度
define('IMAGE_HEIGHT', 280);//图片最小的高度

?>
[如何才能获得应用的Key]
在管理中心的应用页里面可以找到!

Index.php 应用首页 用于跳转授权页

<?php
session_start();

include 'config.php';
include 'saetv2.ex.class.php';
$weibo = new SaeTOAuthV2(APP_Key, APP_Secret);

$code_url = $weibo->getAuthorizeURL(Call_Back);
echo '<script>location.href="'.$code_url.'";</script>';
?>

Key.php 应用授权页 用于授权

<?php
session_start();

include 'config.php';
include 'saetv2.ex.class.php';
$weibo = new SaeTOAuthV2(APP_Key, APP_Secret);

    if(isset($_REQUEST['code'])){
        $keys = array();
        $keys['code'] = $_REQUEST['code'];
        $keys['redirect_uri'] = Call_Back;
        
        try {
            $token = $weibo->getAccessToken( 'code', $keys ) ;
        }catch (OAuthException $error) {
            
        }
    }
    
    if($token){
        $_SESSION['token'] = $token;
        setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
        
        echo '<script>alert("授权完成");location.href="add.php";</script>';

    }else{
        echo '<script>alert("授权失败");</script>';
    }

?>

Catch.php 图片抓取

<?php
exit;
include 'config.php';

$sort = array('games?q=CG', 'games?q=人设', 'games?q=卡牌', 'beauty');

foreach($sort as $index => $values){
    
    $catch_url = 'https://huaban.com/favorite/'.$values.'/';

    $box[] = catch_pic($catch_url, $values);

}

for($i = 0; $i<count($box); $i++){
    for($j = 0; $j<count($box[$i]); $j++){
        $main[] = $box[$i][$j];
    }
    
}

unset($box);
shuffle($main);

//print_r($main);

    /***
     * 写入数据库
     ***/

    $num = count($main);
    
    for($i = 0; $i < $num; $i++){

        $name = rand(100000,999999);
            
        mysql_query('insert into picture values(0, "'.$main[$i]['sort'].'_'.$name.'", "hasn\'t share key", "'.date('Y-m-d H:i:s').'", "'.$main[$i]['sort'].'", "'.$main[$i]['type'].'","true", "'.$main[$i]['key'].'")');
    
    }

    echo '<p>任务完成</p>';

/***
 * Function Catch_Pic
 ***/

function catch_pic($catch_url, $sort){
    
    /***
     * 抓取链接
     ***/
    
    $f = new SaeFetchurl();
    $page = $f->fetch($catch_url);
    
    preg_match_all('/(?<=app\.page\[\"pins\"\] = \[)([\d\D]*?)(?=app\.page\[\"promotions\"\])/', $page, $box);
    $json = $box[0];
    
    preg_match_all('/(?<=\"key\"\:\")([\d\D]*?)(?=\"\,)/', $json[0], $box);
    $key = $box[0];
    
    preg_match_all('/(?<=\"type\"\:\")([\d\D]*?)(?=\"\,)/', $json[0], $box);
    $type = $box[0];
    
    /***
     * 验证数组
     ***/
    
    if(count($key) == count($type)){
        $num = count($key);
    }else{
        echo '<p>抓取出错</p>';
        exit;
    }
    
    /***
     * 整合数组
     ***/
    
    unset($box);
    unset($main);
    
    for($i = 0; $i < $num; $i++){
        $images_type = images_type($type[$i]);
        
        if($images_type){
            $box[$i]['key'] = $key[$i];
            $box[$i]['sort'] = $sort;
            
            if(strstr($box[$i]['sort'], '?')){
                preg_match_all('/([\d\D]*?)(?=\?)/', $box[$i]['sort'], $main);
                $box[$i]['sort'] = $main[0][0];
            }

            $box[$i]['type'] = $images_type;
            
        }else{
            unset($box[$i]);
        }
    
    }
    
    sort($box);
    
    return $box;
    //print_r($box);
}

?>

Show.php 调用图片

<?php
include 'config.php';

    if($_GET['share']!=''){
        
        $select = mysql_fetch_array(mysql_query('select * from picture where share = "'.$_GET['share'].'"'));

        $stor = new SaeStorage();
        $img_data = $stor->read($storage, substr($select['date'], 0, 10).'/'.$select['share'].'.'.$select['suffix']);

        if($img_data!=''){
            $img = new SaeImage($img_data);
            $font = array("name"=>SAE_MicroHei, "size"=>10, "weight"=>180, "color"=>"#ffffff");
            $img->annotate($copy, 1, SAE_SouthWest, $font);
            
            header('Content-type: image/'.$select['suffix']);
            $img->exec($select['suffix'], true);
        }

    }
?>

Add.php 发布微博

<?php

if($_GET['key']==''){
    exit;
}

session_start();

include 'config.php';
include 'saetv2.ex.class.php';

/***
 * SaeTOAuthV2
 ***/

$weibo = new SaeTOAuthV2(APP_Key, APP_Secret);

/***
 * 手动更新Key
 ***/

//mysql_query('update user set token ="'.$_SESSION['token']['access_token'].'" where id = 1');
//exit;

/***
 * SaeTClientV2
 ***/

$select = mysql_fetch_array(mysql_query('select * from user where id = 1'));
$pic_id = $select['num'];
$token = $select['token'];

$weibo = new SaeTClientV2(APP_Key, APP_Secret, $token);

$ms = $weibo->home_timeline();
$uid_get = $weibo->get_uid();
$uid = $uid_get['uid'];
$user_message = $weibo->show_user_by_id($uid);

echo '<p>'.$user_message['screen_name'];

/***
 * 读取数量
 ***/

unset($select);

while(is_null($select[0])){
    $select = mysql_fetch_array(mysql_query('select * from picture where id = '.$pic_id));

    if(is_null($select[0])){
        $pic_id++;
    }
    
}

$pic_max = mysql_fetch_array(mysql_query('select max(id) from picture'));

/***
 * 写入图片
 ***/

if($pic_id <= $pic_max[0]){
    $stor = new SaeStorage();
    $f = new SaeFetchurl();
    
    unset($img_data);
    while($img_data == ''){
        $img_data = $f->fetch('https://img.hb.aicdn.com/'.$select['key'].'_fw658');
    }

    if($img_data != ''){
        $image = new SaeImage($img_data);
        $image_info = $image->getImageAttr();
        
        if($image_info[0]>=IMAGE_WIDTH && $image_info[1]>=IMAGE_HEIGHT){
            $share = md5(md5($img_data));
            mysql_query('update picture set share = "'.$share.'", date = "'.date('Y-m-d H:i:s').'" where id='.$select['id']);
    
            $name = date('Y-m-d').'/'.$share.'.'.$select['suffix'];
            
            $stor->write($storage, $name, $img_data);
            
        }else{
            mysql_query('delete from picture where id='.$pic_id);

            mysql_query('update user set num = '.($pic_id+1).' where id = 1');
            
            echo ':图片大小不符合';
            exit;
        }

    }else{
        mysql_query('update user set num = '.$pic_id.' where id = 1');
        
        echo ':数据抓取失败';

        exit;
    }
    
    /***
     * 发表微博
     ***/
    
    unset($img_data);
    $img_data = $f->fetch('https://msae.sinaapp.com/show.php?share='.$share);
    
    if($img_data!=''){
        $box = $weibo->upload('#美图推送# Hi!我是推送君,请多多包涵~', 'https://msae.sinaapp.com/show.php?share='.$share);
        
        if(isset($box['error_code']) && $box['error_code'] > 0){
            echo ":微博发送失败,错误:{$box['error_code']}:{$box['error']}";

        }else{

            $select = mysql_query('update user set num = '.($pic_id+1).' where id = 1');
            
            /*if($select!='true'){
                unset($select);
                while($select!='true'){
                    $select = mysql_query('update user set num = '.($pic_id+1).' where id = 1');
                }
            }*/
            
            if($select){
                echo ":微博发送成功";
            }else{
                echo ':数据库出错';
            }
            
        }
        
    }else{
        echo ':Storage拉取出错';
    }

}else{
    echo ':数据抓取失败';
}

?>

除了PHP外,我们还要用到MySql数据库来存放图片信息和用户信息。

Table Picture 存放图片信息

CREATE TABLE IF NOT EXISTS `picture` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `share` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `date` datetime NOT NULL,
  `sort` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `suffix` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `key` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `key` (`key`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Table User 存放用户信息

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `num` int(25) NOT NULL,
  `token` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

还有最重要的计划任务(在Config.yaml里面加入):

cron:
- description: cron_catch
  url: /catch.php
  schedule: "*/1 * * * *"
- description: cron_add
  url: /add.php
  schedule: "*/1 * * * *"
[数据表如何使用]
按照上面的表结构建好表后,在User表中插入以下数据:
INSERT INTO `user` (`id`, `num`, `token`) VALUES (1, 1, '新浪API的授权密匙');

[如何获得新浪API的授权密匙]

在 Add.php 文件里面有个“手动更新Key”的注释,注释下面有2行代码。

把注释删掉然后访问 Add.php 文件即可自动将密匙加入数据库。

加入了数据库后记得把那两行代码注释掉,否则无法使用下面的代码!!

[效果预览]

请翻看旧的微博:https://weibo.com/312388450

标签:新浪, 微博, 自动, 推送, 美图

该文章由 Shiqi 原创并发布在 被遗忘的曙光 技术博客

转载请标明来源:https://fdawn.com/PHP/2.html

仅有 1 条评论

  1. Melissa

    That's way the betsset answer so far!

添加新评论