Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tweet news in terminal toolbar #3757

Merged
merged 59 commits into from
Feb 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
b589beb
Add tweet news in terminal toolbar
DidierRLopes Dec 11, 2022
fc0152f
allow to store tweet news settings
DidierRLopes Dec 11, 2022
29e599c
Merge branch 'main' into newsbanner
DidierRLopes Dec 11, 2022
34c6807
update dependencies
DidierRLopes Dec 12, 2022
a44efc0
Add tweet news in terminal toolbar
DidierRLopes Dec 11, 2022
f319098
merge
DidierRLopes Dec 13, 2022
8708765
lint
DidierRLopes Dec 13, 2022
e77bbd2
dependencies
DidierRLopes Dec 13, 2022
913e5ae
5s timeout for twitter api
DidierRLopes Dec 13, 2022
491c30f
Merge branch 'main' into newsbanner
jmaslek Dec 15, 2022
586d756
poetry update for resolve
jmaslek Dec 15, 2022
aca0164
reqs
jmaslek Dec 15, 2022
c901dee
Merge branch 'main' into newsbanner
DidierRLopes Dec 17, 2022
ccbc347
set news to false by default
DidierRLopes Dec 17, 2022
812c301
update tweepy
DidierRLopes Dec 17, 2022
97a16d6
update reqs
DidierRLopes Dec 18, 2022
0a67034
update reqs again?
DidierRLopes Dec 18, 2022
1d23135
update setuptools
DidierRLopes Dec 18, 2022
818d3ba
small improv
DidierRLopes Dec 22, 2022
c1eaff3
Add tweet news in terminal toolbar
DidierRLopes Dec 11, 2022
81a406f
merge main
DidierRLopes Dec 22, 2022
ed8e1ef
update packages
DidierRLopes Dec 22, 2022
1791427
fix conflicts
DidierRLopes Jan 15, 2023
3b332d4
resolve conflicts
DidierRLopes Feb 1, 2023
4d27b71
black linting
DidierRLopes Feb 1, 2023
a5785f8
black formatting
DidierRLopes Feb 1, 2023
5bdc7b0
ruff fixes
DidierRLopes Feb 1, 2023
3568c55
fix settings controller
DidierRLopes Feb 1, 2023
9495273
Reqs
jmaslek Feb 1, 2023
c51e186
fix tz issue
DidierRLopes Feb 2, 2023
070ef57
add keywords selection
DidierRLopes Feb 2, 2023
4f0ed5f
linting
DidierRLopes Feb 2, 2023
5b0c97c
helper funcs mypy
DidierRLopes Feb 2, 2023
cec8575
pylint fixes
DidierRLopes Feb 2, 2023
1fd5a47
Checkout poetry.lock + pyproject.toml
Chavithra Feb 2, 2023
aeb97ac
Update dependencies
Chavithra Feb 2, 2023
e41518a
Remove integration test file
Chavithra Feb 2, 2023
c0da568
Merge branch 'develop' into newsbanner
Chavithra Feb 2, 2023
685b9bf
News Toolbar : Fix bugs
Chavithra Feb 21, 2023
f49e6f3
Tests : News Toolbar
Chavithra Feb 21, 2023
fad9cde
Merge remote-tracking branch 'origin/develop' into newsbanner
Chavithra Feb 21, 2023
5334d52
Update dependencies
Chavithra Feb 21, 2023
202484f
Tests : change variable name
Chavithra Feb 21, 2023
0480c2e
Remove unused keys
Chavithra Feb 22, 2023
a24744b
Remove unecessary global variable
Chavithra Feb 22, 2023
f4af57f
Fix linting
Chavithra Feb 22, 2023
e971e06
Lighter API call
Chavithra Feb 22, 2023
f8cab4f
Ruff
Chavithra Feb 22, 2023
500999e
Linting + Remove keys
Chavithra Feb 22, 2023
61da238
Linting
Chavithra Feb 22, 2023
4493f1a
Dotenv loading issue.
Chavithra Feb 22, 2023
f5d6d0f
Merge branch 'develop' into newsbanner
Chavithra Feb 22, 2023
4f2b6ee
Ruff
Chavithra Feb 22, 2023
f51beb0
Revert "Dotenv loading issue."
Chavithra Feb 22, 2023
206f753
Merge branch 'develop' into newsbanner
Chavithra Feb 22, 2023
c6c9830
Tests : fix
Chavithra Feb 22, 2023
9ebb009
Tests : fix test_settings_controller.py
Chavithra Feb 23, 2023
797a3f0
Twitter Toolbar : avoid checking API when not enabled
Chavithra Feb 23, 2023
4259f5c
Tests : news toolbar
Chavithra Feb 23, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions openbb_terminal/config_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,6 @@
API_POLYGON_KEY = os.getenv("OPENBB_API_POLYGON_KEY") or "REPLACE_ME"

# https://developer.twitter.com
API_TWITTER_KEY = os.getenv("OPENBB_API_TWITTER_KEY") or "REPLACE_ME"
API_TWITTER_SECRET_KEY = os.getenv("OPENBB_API_TWITTER_SECRET_KEY") or "REPLACE_ME"
API_TWITTER_BEARER_TOKEN = os.getenv("OPENBB_API_TWITTER_BEARER_TOKEN") or "REPLACE_ME"

# https://fred.stlouisfed.org/docs/api/api_key.html
Expand Down
3 changes: 2 additions & 1 deletion openbb_terminal/economy/economy_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,8 @@ def call_macro(self, other_args: List[str]):
self.DATASETS["macro"].drop(column, axis=1, inplace=True)

self.DATASETS["macro"] = pd.concat(
[self.DATASETS["macro"], df], axis=1
[self.DATASETS["macro"], df],
axis=1,
)

# update units dict
Expand Down
32 changes: 32 additions & 0 deletions openbb_terminal/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,38 @@
# Toolbar hint
TOOLBAR_HINT = load_env_vars("OPENBB_TOOLBAR_HINT", strtobool, True, "featflags")

# Toolbar Twitter news
TOOLBAR_TWEET_NEWS = load_env_vars(
"OPENBB_TOOLBAR_TWEET_NEWS", strtobool, False, "featflags"
)

# Toolbar Twitter news seconds between updates being checked
TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES = load_env_vars(
"OPENBB_TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES", int, 300, "settings"
)

# Toolbar Twitter news accounts to track
TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK = load_env_vars(
"OPENBB_TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK",
str,
"WatcherGuru,unusual_whales,gurgavin,CBSNews",
"settings",
)

# Toolbar Twitter news keywords to look for
TOOLBAR_TWEET_NEWS_KEYWORDS = load_env_vars(
"OPENBB_TOOLBAR_TWEET_NEWS_KEYWORDS",
str,
"BREAKING,JUST IN",
"settings",
)


# Toolbar Twitter news number of last tweets to read
TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ = load_env_vars(
"OPENBB_TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ", int, 3, "settings"
)

# Select language to be used
USE_LANGUAGE = str(os.getenv("OPENBB_USE_LANGUAGE", "en"))

Expand Down
111 changes: 109 additions & 2 deletions openbb_terminal/helper_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
import pandas.io.formats.format
import pytz
import requests
import tweepy
import yfinance as yf
from dateutil.relativedelta import relativedelta
from holidays import US as us_holidays
from pandas._config.config import get_option
from pandas.plotting import register_matplotlib_converters
Expand All @@ -48,6 +50,22 @@
)
from openbb_terminal.rich_config import console

try:
twitter_api = tweepy.API(
tweepy.OAuth2BearerHandler(
cfg.API_TWITTER_BEARER_TOKEN,
),
timeout=5,
)
if obbff.TOOLBAR_TWEET_NEWS and cfg.API_TWITTER_BEARER_TOKEN != "REPLACE_ME":
# A test to ensure that the Twitter API key is correct,
# otherwise we disable the Toolbar with Tweet News
twitter_api.get_user(screen_name="openbb_finance")
except tweepy.errors.Unauthorized:
# Set toolbar tweet news to False because the Twitter API is not set up correctly
obbff.TOOLBAR_TWEET_NEWS = False


logger = logging.getLogger(__name__)

register_matplotlib_converters()
Expand All @@ -63,11 +81,12 @@
MENU_QUIT = 1
MENU_RESET = 2

LAST_TWEET_NEWS_UPDATE_CHECK_TIME = None

# Command location path to be shown in the figures depending on watermark flag
command_location = ""


# pylint: disable=R0912
# pylint: disable=R1702,R0912


# pylint: disable=global-statement
Expand Down Expand Up @@ -1833,6 +1852,94 @@ def str_date_to_timestamp(date: str) -> int:
return date_ts


def update_news_from_tweet_to_be_displayed() -> str:
"""Update news from tweet to be displayed.

Returns
-------
str
The news from tweet to be displayed
"""
global LAST_TWEET_NEWS_UPDATE_CHECK_TIME

news_tweet = ""

# Check whether it has passed a certain amount of time since the last news update
if LAST_TWEET_NEWS_UPDATE_CHECK_TIME is None or (
(datetime.now(pytz.utc) - LAST_TWEET_NEWS_UPDATE_CHECK_TIME).total_seconds()
> obbff.TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES
):
# This doesn't depende on the time of the tweet but the time that the check was made
LAST_TWEET_NEWS_UPDATE_CHECK_TIME = datetime.now(pytz.utc)

dhours = 0
dminutes = 0
# Get timezone that corresponds to the user
if obbff.USE_DATETIME and get_user_timezone_or_invalid() != "INVALID":
utcnow = pytz.timezone("utc").localize(datetime.utcnow()) # generic time
here = utcnow.astimezone(pytz.timezone("Etc/UTC")).replace(tzinfo=None)
there = utcnow.astimezone(pytz.timezone(get_user_timezone())).replace(
tzinfo=None
)

offset = relativedelta(here, there)
dhours = offset.hours
dminutes = offset.minutes

if "," in obbff.TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK:
news_sources_twitter_handles = (
obbff.TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK.split(",")
)
else:
news_sources_twitter_handles = [obbff.TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK]

news_tweet_to_use = ""
handle_to_use = ""
url = ""
last_tweet_dt: Optional[datetime] = None
for handle in news_sources_twitter_handles:
try:
# Get last N tweets from each handle
timeline = twitter_api.user_timeline(
screen_name=handle,
count=obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ,
)
timeline = timeline[: obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ]
for last_tweet in timeline:
keywords = obbff.TOOLBAR_TWEET_NEWS_KEYWORDS.split(",")
more_recent = (
last_tweet_dt is None or last_tweet.created_at > last_tweet_dt
)
with_keyword = any(key in last_tweet.text for key in keywords)

if more_recent and with_keyword:
handle_to_use = handle
last_tweet_dt = last_tweet.created_at

news_tweet_to_use = last_tweet.text

url = f"https://twitter.com/x/status/{last_tweet.id_str}"

# In case the handle provided doesn't exist, we skip it
except tweepy.errors.NotFound:
pass

if last_tweet_dt and news_tweet_to_use:
tweet_hr = f"{last_tweet_dt.hour}"
tweet_min = f"{last_tweet_dt.minute}"
# Update time based on timezone specified by user
if (
obbff.USE_DATETIME and get_user_timezone_or_invalid() != "INVALID"
) and (dhours > 0 or dminutes > 0):
tweet_hr = f"{round((int(last_tweet_dt.hour) - dhours) % 60):02}"
tweet_min = f"{round((int(last_tweet_dt.minute) - dminutes) % 60):02}"

# Update NEWS_TWEET with the new news tweet found
news_tweet = f"{tweet_hr}:{tweet_min} - @{handle_to_use} - {url}\n\n{news_tweet_to_use}"

return news_tweet


def check_start_less_than_end(start_date: str, end_date: str) -> bool:
"""Check if start_date is equal to end_date.

Expand Down
2 changes: 0 additions & 2 deletions openbb_terminal/keys_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,8 +515,6 @@ def call_twitter(self, other_args: List[str]):
ns_parser = self.parse_simple_args(parser, other_args)
if ns_parser:
self.status_dict["twitter"] = keys_model.set_twitter_key(
key=ns_parser.key,
secret=ns_parser.secret,
access_token=ns_parser.token,
persist=True,
show_output=True,
Expand Down
11 changes: 1 addition & 10 deletions openbb_terminal/keys_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,8 +1090,6 @@ def check_bitquery_key(show_output: bool = False) -> str:


def set_twitter_key(
key: str,
secret: str,
access_token: str,
persist: bool = False,
show_output: bool = False,
Expand Down Expand Up @@ -1128,8 +1126,6 @@ def set_twitter_key(
)
"""

set_key("OPENBB_API_TWITTER_KEY", key, persist)
set_key("OPENBB_API_TWITTER_SECRET_KEY", secret, persist)
set_key("OPENBB_API_TWITTER_BEARER_TOKEN", access_token, persist)

return check_twitter_key(show_output)
Expand All @@ -1149,12 +1145,7 @@ def check_twitter_key(show_output: bool = False) -> str:
Status of key set
"""

twitter_keys = [
cfg.API_TWITTER_KEY,
cfg.API_TWITTER_SECRET_KEY,
cfg.API_TWITTER_BEARER_TOKEN,
]
if "REPLACE_ME" in twitter_keys:
if cfg.API_TWITTER_BEARER_TOKEN == "REPLACE_ME":
logger.info("Twitter key not defined")
status = KeyStatus.NOT_DEFINED
else:
Expand Down
8 changes: 7 additions & 1 deletion openbb_terminal/miscellaneous/i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ en:
featflags/ion: interactive matplotlib mode
featflags/watermark: watermark in figures
featflags/cmdloc: command location displayed in figures
featflags/tbhint: displays usage hints in a bottom toolbar
featflags/tbhint: displays usage hints in the bottom toolbar
settings/_info_: Settings through environment variables
settings/colors: set your own terminal colors
settings/autoscaling: plot autoscaling
Expand Down Expand Up @@ -89,6 +89,12 @@ en:
settings/_timezone: Timezone
settings/source: specify data source file
settings/_data_source: Data sources
settings/tbnews: displays tweets news in the bottom toolbar
settings/tweetnews: tweak tweet news parameters
settings/_tbnu: Time (in seconds) between tweet news updates
settings/_tatt: Twitter accounts to track
settings/_nttli: Number of tweets to look into from each account
settings/_tk: Keywords to look for in tweets
_toolkits_: OpenBB Toolkits
stocks: access historical pricing data, options, sector and industry, and overall due diligence
crypto: dive into onchain data, tokenomics, circulation supply, nfts and more
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"info": "rgb(224,131,48)",
"cmds": "#2A7C6E",
"param": "rgb(247,206,70)",
"menu": "#427A2E",
"src": "rgb(216,90,64)",
"unvl": "grey30",
"help": "#FAC900"
}
56 changes: 55 additions & 1 deletion openbb_terminal/parent_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# pylint: disable=C0301,C0302,R0902,global-statement,too-many-boolean-expressions

# IMPORTS STANDARD
import argparse
import difflib
import json
Expand All @@ -13,12 +14,14 @@
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Union

# IMPORTS THIRDPARTY
import numpy as np
import pandas as pd
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style
from rich.markdown import Markdown

# IMPORTS INTERNAL
from openbb_terminal import feature_flags as obbff
from openbb_terminal.config_terminal import theme
from openbb_terminal.core.completer.choices import build_controller_choice_map
Expand All @@ -41,6 +44,7 @@
set_command_location,
support_message,
system_clear,
update_news_from_tweet_to_be_displayed,
valid_date,
)
from openbb_terminal.menu import session
Expand All @@ -51,6 +55,8 @@

logger = logging.getLogger(__name__)

# pylint: disable=R0912

NO_EXPORT = 0
EXPORT_ONLY_RAW_DATA_ALLOWED = 1
EXPORT_ONLY_FIGURES_ALLOWED = 2
Expand Down Expand Up @@ -902,7 +908,55 @@ def menu(self, custom_path_menu_above: str = ""):
try:
# Get input from user using auto-completion
if session and obbff.USE_PROMPT_TOOLKIT:
if bool(obbff.TOOLBAR_HINT):
# Check if tweet news is enabled
if obbff.TOOLBAR_TWEET_NEWS:
news_tweet = update_news_from_tweet_to_be_displayed()

# Check if there is a valid tweet news to be displayed
if news_tweet:
an_input = session.prompt(
f"{get_flair()} {self.PATH} $ ",
completer=self.completer,
search_ignore_case=True,
bottom_toolbar=HTML(news_tweet),
style=Style.from_dict(
{
"bottom-toolbar": "#ffffff bg:#333333",
}
),
)

else:
# Check if toolbar hint was enabled
if obbff.TOOLBAR_HINT:
an_input = session.prompt(
f"{get_flair()} {self.PATH} $ ",
completer=self.completer,
search_ignore_case=True,
bottom_toolbar=HTML(
'<style bg="ansiblack" fg="ansiwhite">[h]</style> help menu '
'<style bg="ansiblack" fg="ansiwhite">[q]</style> return to previous menu'
' <style bg="ansiblack" fg="ansiwhite">[e]</style> exit terminal '
'<style bg="ansiblack" fg="ansiwhite">[cmd -h]</style> '
"see usage and available options "
f'<style bg="ansiblack" fg="ansiwhite">[about (cmd/menu)]</style> '
f"{self.path[-1].capitalize()} (cmd/menu) Documentation"
),
style=Style.from_dict(
{
"bottom-toolbar": "#ffffff bg:#333333",
}
),
)
else:
an_input = session.prompt(
f"{get_flair()} {self.PATH} $ ",
completer=self.completer,
search_ignore_case=True,
)

# Check if toolbar hint was enabled
elif obbff.TOOLBAR_HINT:
an_input = session.prompt(
f"{get_flair()} {self.PATH} $ ",
completer=self.completer,
Expand Down
Loading