# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).

__all__ = ['auth', 'twitter_api', 'example_rel', 'tweet_text', 'send_tweet', 'install']

# Cell
from fastcore.utils import *
from fastcore.script import *

# Cell
import tweepy

# Cell
@call_parse
def auth():
    "Function for `tweetrel-auth` CLI command"
    cons = input('Enter consumer key and secret, separated by a space: ').split()
    auth = tweepy.OAuthHandler(*cons)
    print('Go to this URL and login:')
    print(auth.get_authorization_url())
    code = input('Paste code here: ')
    print('Your keys are:')
    print(' '.join(auth.get_access_token(code)))

# Cell
from ghapi import *

# Cell
def twitter_api():
    consumer_key,consumer_secret,access_token,access_token_secret = context_secrets.TWITTER.split()
    auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
    auth.set_access_token(access_token,access_token_secret)
    return tweepy.API(auth)

# Cell
example_rel = example_payload(Event.release)

# Cell
def tweet_text(payload):
    def_tmpl = "New #{repo} release: v{tag_name}. {html_url}\n\n{body}"
    tweet_tmpl = os.getenv('TWEETREL_TEMPLATE', def_tmpl)
    rel = payload.release
    owner,repo = example_rel.repository.full_name.split('/')
    res = tweet_tmpl.format(repo=repo, tag_name=rel.tag_name, html_url=rel.html_url, body=rel.body)
    if len(res)<=280: return res
    return res[:279] + "…"

# Cell
def send_tweet():
    payload = context_github.event
    if 'workflow' in payload: payload = example_payload(Event.release)
    if payload.action == 'published': return twitter_api().update_status(tweet_text(payload))

# Cell
@call_parse
def install():
    fill_workflow_templates(
        name='tweet', event="release:\n  types: [published]",
        run='pip install -Uq tweetrel',
        context=env_contexts('secrets'),
        script="import tweetrel\ntweetrel.send_tweet()"
    )