82 lines
3.2 KiB
Python
82 lines
3.2 KiB
Python
import requests
|
|
import json
|
|
from requests_oauthlib import OAuth1Session
|
|
from flask import Blueprint, current_app, request, jsonify
|
|
from ayct_backend.twitter.models import *
|
|
from ayct_backend.campaign.models import *
|
|
|
|
campaign = Blueprint('campaign', __name__)
|
|
|
|
@campaign.route('/campaign', methods=['GET'])
|
|
def get_twitter_campaigns():
|
|
twitter_campaigns = TwitterCampaign.query.all()
|
|
|
|
campaigns = []
|
|
|
|
for campaign in twitter_campaigns:
|
|
campaign_data = {}
|
|
campaign_data['campaign_name'] = campaign.campaign_name
|
|
campaign_data['twitter_account_id'] = campaign.twitter_account_id
|
|
campaign_data['user_input'] = campaign.user_input
|
|
campaign_data['generated_content'] = campaign.generated_content
|
|
campaign_data['twitter_post_id'] = campaign.twitter_post_id
|
|
campaigns.append(campaign_data)
|
|
|
|
return jsonify({
|
|
"twitter_campaigns": campaigns
|
|
}), 200
|
|
|
|
@campaign.route('/campaign', methods=['POST'])
|
|
def add_twitter_account():
|
|
content_type = request.headers.get('Content-Type')
|
|
if (content_type == 'application/json'):
|
|
request_json = request.json
|
|
if not request_json['campaign_name'] or not request_json['user_input'] or not request_json['twitter_account_id']:
|
|
return "Invalid request!", 400
|
|
else:
|
|
consumer_key = current_app.config["TWITTER_CONSUMER_KEY"]
|
|
consumer_secret = current_app.config["TWITTER_CONSUMER_SECERT"]
|
|
|
|
twitter_account = TwitterAccount.query.filter_by(twitter_account_id=request_json['twitter_account_id']).first()
|
|
|
|
# generate campaign content
|
|
core_url = 'http://65.108.80.28:4999/generate'
|
|
payload = {
|
|
"data": request_json['user_input'],
|
|
"length": 400
|
|
}
|
|
|
|
response = requests.post(core_url, headers={"Content-Type":"application/json"}, data=json.dumps(payload))
|
|
|
|
generated_content = response.content.decode("utf-8").replace('<|endoftext|>', '')
|
|
#generated_content = "This is wonderful post content generated by our very smart core API!"
|
|
|
|
# create post on twitter
|
|
oauth = OAuth1Session(
|
|
consumer_key,
|
|
client_secret=consumer_secret,
|
|
resource_owner_key=twitter_account.access_token,
|
|
resource_owner_secret=twitter_account.access_token_secret,
|
|
)
|
|
|
|
response = oauth.post(
|
|
"https://api.twitter.com/2/tweets",
|
|
json={"text": generated_content[0:260]},
|
|
).json()['data']
|
|
|
|
# save campaign to database
|
|
new_twitter_campaign = TwitterCampaign(
|
|
campaign_name = request_json['campaign_name'],
|
|
twitter_account_id = request_json['twitter_account_id'],
|
|
user_input = request_json['user_input'],
|
|
generated_content = generated_content[0:260],
|
|
twitter_post_id = response['id']
|
|
)
|
|
|
|
campaign_db.session.add(new_twitter_campaign)
|
|
campaign_db.session.commit()
|
|
|
|
return "Campaign succesfully created.", 201
|
|
else:
|
|
return "Content-type not supported!", 400
|