Попытка получить Twitter-бота для публикации двух изображений одновременно - PullRequest
1 голос
/ 29 мая 2020

Я работаю над твиттер-ботом, целью которого является размещение двух изображений вместе со строкой текста. Я использую node.js (в первый раз, наверное, стоит добавить) и пакет Twit .

У меня множество проблем, многие из которых, вероятно, просто из-за того, что я новичок, но я действительно не могу понять, как правильно выводить эту чертову штуку. Мне удалось получить текст и одно изображение для вывода, но я пытаюсь выплюнуть сразу два изображения.

Основной блок бота использует следующий код для создания и планирования твита:

function mainPostBot() {
console.log("Now assembling a new tweet.");

var leftCard = getRandomNumber(1, 36);
    console.log("The left card is #" + leftCard + ", " + cardNames[leftCard] + ".");
    // Generates a random number for the left card.
var leftImagePath = path.join(__dirname, '/leftImage/' + imageArray[leftCard]);
    console.log("The left image's path is " + leftImagePath);
    // Gives the file path to access the correct image for the left.

var rightCard = getRandomNumber(1, 36);
    console.log("The right card is #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card.
while (leftCard == rightCard) {
    var rightCard = getRandomNumber(1, 36);
    console.log("Whoops! The right card is now #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card in the case of doubles.
}
var rightImagePath = path.join(__dirname, '/rightImage/' + imageArray[rightCard]);
    console.log("The right image's path is " + rightImagePath);
    // Gives the file path to access the correct image for the left.

console.log('Encoding the images...');
    var b64contentLeft = fs.readFileSync(leftImagePath, { encoding: 'base64' });
    var b64contentRight = fs.readFileSync(rightImagePath, { encoding: 'base64' });
    var bothImages = (b64contentLeft + "," + b64contentRight);
    // This encodes the images in base64, which twitter needs. I guess. I dunno, man.

var tweetText = (jsUcfirst(cardNames[leftCard]) + ' and ' + cardNames[rightCard] + '. (#' + leftCard + " " + cardCorrespond[leftCard] + "/#" + rightCard + " " + cardCorrespond[rightCard] + ")");
// This constructs the grammar of the tweet.
// jsUcfirst capitalizes the first letter of a string so it lets me cheat a sentence start.

var tweetTime = getRandomNumber(1000*60*60*4, 1000*60*60*24*3+1);
    // Generates an amount of time before the next tweet.

sendTweet(tweetText, bothImages, tweetTime);

setTimeout(mainPostBot, tweetTime);
}

mainPostBot();

cardNames, cardCorrespond и imageArray - это просто большие массивы в верхней части программы, в которых перечислены имена изображений, некоторая информация о них и их имена файлов, соответственно:

var cardNames = new Array(
    "the Fool", //This one will never be called bc of the number generator and it's fun bc, y'know, Tarot
    "the Rider","the Clover","the Ship","the House","the Tree","the Clouds","the Snake","the Coffin","the Bouquet","the Scythe","the Whip", //"the Nae Nae",
    "the Birds","the Child","the Fox","the Bear","the Stars","the Stork","the Dog","the Tower","the Garden","the Mountain","the Crossroads",
    "the Mice","the Heart","the Ring","the Book","the Letter","the Gentleman","the Lady","the Lily","the Sun","the Moon","the Key","the Fish",
    "the Anchor","the Cross"
    );

var cardCorrespond = new Array(
    " ","9♥","6♦","10♠","K♥","7♥","K♣","Q♣","9♦","Q♠","J♦","J♣","7♦","J♠","9♣","10♣","6♥","Q♥","10♥",
    "6♠","8♠","8♣","Q♦","7♣","J♥","A♣","10♦","7♠","A♥","A♠","K♠","A♦","8♥","8♦","K♦","9♠","6♣"
    );

var imageArray = new Array(
    " ","01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png","12.png","13.png",
    "14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png","22.png","23.png","24.png","25.png","26.png",
    "27.png","28.png","29.png","30.png","31.png","32.png","33.png","34.png","35.png","36.png"
    );

И как только mainPostBot полностью сконструирует твит, он доставляется в sendTweet:

function sendTweet(text, images, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: images }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the images.");
            console.log(err);
        } else {
            console.log('Images uploaded!');
            console.log("Now tweeting...")

            T.post('statuses/update', {
                status: text,
                media_ids: new Array(data.media_id_string)
            }, function(err, data, response){
                if (err) {
                    console.log("An error has occurred during posting.");
                    console.log(err);
                } else {
                    console.log("Post successful!");
                    console.log("The tweet says:" + text);
                    console.log("The next tweet will send in " + msToTime(time) + "!");
                }
            });
        }
    });
}

Есть идеи? Я открыт для использования других пакетов npm, конечно, но я просто не могу понять, почему это не работает как есть. Спасибо за чтение и дайте мне знать, если вам понадобятся другие части кода.

РЕДАКТИРОВАТЬ 1: Мой сосед по комнате, который также балуется такими вещами, нашел потенциально полезную ссылку на github для другого пакета, node-twitter. В этой ссылке плакат объясняет, что изображения должны доставляться в виде строки, разделенной запятыми, поэтому я добавил некоторые изменения в mainPostBot и sendTweet, в основном при передаче данных изображения b64.

EDIT 2: Те изменения теперь отражены в приведенном выше коде, а также некоторые другие исправления, которые я внес в проект в целом. Я дошел до точки, когда все снова идет гладко (обнаружил недостающую скобку, я отстой с этим кодированием), и твиты успешно публикуются, но, как и раньше, я не могу пройти второе изображение. Сосед по комнате, который помогал раньше, предлагает просто выкачивать статические c отдельные изображения для каждой возможной комбинации карт, но должно быть более элегантное решение. Опять же, любые идеи могут спасти неделю моей странной возни в спальне, и я ценю любой взгляд на это.

1 Ответ

1 голос
/ 29 мая 2020

Потребовалось много повозиться, но я разобрался. Каждое изображение должно быть загружено в твиттер индивидуально, поэтому после загрузки изображения я сохраняю его data.media_id_string в переменной, а затем загружаю эти значения в твит в виде массива.

Я удалил строку из mainPostBot, где я объединил b64contentLeft и b64contentRight и добавил их в код sendTweet, используя возвращенные строки данных. Теперь я вызываю sendTweet () с помощью:

sendTweet(tweetText, b64contentLeft, b64contentRight, tweetTime);

И sendTweet () теперь выглядит так:

function sendTweet(text, leftimage, rightimage, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: leftimage }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the left image.");
            console.log(err);
        } else {
            console.log('Left image uploaded!');
            var leftID = data.media_id_string;

            T.post('media/upload', { media_data: rightimage }, function (err, data, response){
                if (err){
                    console.log("There's an issue uploading the right image.");
                    console.log(err);
                } else {
                    console.log('Right image uploaded!');
                    var rightID = data.media_id_string;
                    var bothImages = ( leftID + "," + rightID );

                    console.log("Now tweeting...")

                    T.post('statuses/update', {
                        status: text,
                        media_ids: new Array(bothImages)
                    }, function(err, data, response){
                        if (err) {
                            console.log("An error has occurred during posting.");
                            console.log(err);
                        } else {
                            console.log("Post successful!");
                            console.log("The tweet says: " + text);
                            console.log("The next tweet will send in " + msToTime(time) + "!");
                        }
                    });
                }
            });
        }
    });
}

По сути, если левое изображение загружается правильно, оно сохранит этот идентификатор, затем попробуйте найти правильное изображение. В случае успеха он также сохранит этот идентификатор, а затем объединит их в строку, разделенную запятой, которая загружается в массив media_ids как bothImages.

Это был кошмар, который нужно было решить, но я хотел убедиться, что это задокументировано на тот случай, если кто-то еще наткнется здесь и ищет тот же ответ.

...