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 8 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
24 changes: 24 additions & 0 deletions openbb_terminal/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,29 @@
# 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, True, "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 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 All @@ -143,6 +166,7 @@
try:
if not WITH_GIT:
import pkg_resources

version = pkg_resources.get_distribution("OpenBB").version
else:
raise Exception("Using git")
Expand Down
96 changes: 94 additions & 2 deletions openbb_terminal/helper_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from pathlib import Path
from typing import List, Union, Optional, Dict
from functools import lru_cache
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from datetime import date as d
import types
from collections.abc import Iterable
Expand Down Expand Up @@ -35,10 +35,12 @@
from screeninfo import get_monitors
import yfinance as yf
import numpy as np
import tweepy

from PIL import Image, ImageDraw

from openbb_terminal.rich_config import console
from openbb_terminal import config_terminal as cfg
from openbb_terminal import feature_flags as obbff
from openbb_terminal import config_plot as cfgPlot
from openbb_terminal.core.config.paths import (
Expand All @@ -48,6 +50,20 @@
)
from openbb_terminal.core.config import paths

try:
twitter_api = tweepy.API(
tweepy.OAuth2BearerHandler(
cfg.API_TWITTER_BEARER_TOKEN,
)
)
# A test to ensure that the Twitter API key is correct,
# otherwise we disable the Toolbar with Tweet News
twitter_api.user_timeline(screen_name="openbb_finance", count=1)
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 @@ -66,8 +82,11 @@
# Command location path to be shown in the figures depending on watermark flag
command_location = ""

NEWS_TWEET = ""
LAST_TWEET_NEWS_UPDATE_CHECK_TIME = datetime.now() - timedelta(hours=1)
Chavithra marked this conversation as resolved.
Show resolved Hide resolved

# pylint: disable=R1702,R0912

# pylint: disable=R0912

# pylint: disable=global-statement
def set_command_location(cmd_loc: str):
Expand Down Expand Up @@ -1879,3 +1898,76 @@ 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

# Check whether it has passed a certain amount of time since the last news update
if (
datetime.now() - LAST_TWEET_NEWS_UPDATE_CHECK_TIME
).seconds > obbff.TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES:
Chavithra marked this conversation as resolved.
Show resolved Hide resolved

# 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()

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 = ""
last_tweet_dt = (datetime.now() - timedelta(hours=1)).replace(
tzinfo=timezone.utc
)
for handle in news_sources_twitter_handles:

try:
# Get last N tweets from each handle
for last_tweet in twitter_api.user_timeline(
screen_name=handle,
count=obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ,
)[: obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ]:
# Check if the tweet contains "JUST IN:" or "BREAKING:"
if "JUST IN" in last_tweet.text or "BREAKING" in last_tweet.text:
# Check if the tweet is newer than the last one
# we want to grab the most recent one
if last_tweet.created_at > last_tweet_dt:
handle_to_use = handle
last_tweet_dt = last_tweet.created_at
news_tweet_to_use = last_tweet.text.replace(
"JUST IN: ", ""
).replace("BREAKING: ", "")

# Get url associated with tweet
if last_tweet.entities:
if "urls" in last_tweet.entities:
if last_tweet.entities["urls"]:
if (
"expanded_url"
in last_tweet.entities["urls"][-1]
):
url = last_tweet.entities["urls"][-1][
"expanded_url"
]

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

if news_tweet_to_use:
global NEWS_TWEET
# Update NEWS_TWEET with the new news tweet found
NEWS_TWEET = f"{last_tweet_dt.hour}:{last_tweet_dt.hour} - @{handle_to_use} - {url}\n\n{news_tweet_to_use}"

return NEWS_TWEET
7 changes: 6 additions & 1 deletion openbb_terminal/miscellaneous/i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,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 @@ -72,6 +72,11 @@ 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
_others_: Others
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"
}
55 changes: 54 additions & 1 deletion openbb_terminal/parent_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
support_message,
system_clear,
valid_date,
update_news_from_tweet_to_be_displayed,
)
from openbb_terminal.rich_config import console, get_ordered_list_sources
from openbb_terminal.stocks import stocks_helper
Expand All @@ -51,6 +52,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 @@ -891,7 +894,57 @@ 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
84 changes: 84 additions & 0 deletions openbb_terminal/settings_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
get_user_timezone_or_invalid,
replace_user_timezone,
set_user_data_folder,
check_positive,
)
from openbb_terminal.menu import session
from openbb_terminal.parent_classes import BaseController
Expand Down Expand Up @@ -54,6 +55,8 @@ class SettingsController(BaseController):
"source",
"flair",
"colors",
"tbnews",
"tweetnews",
]
PATH = "/settings/"

Expand Down Expand Up @@ -132,6 +135,14 @@ def print_help(self):
mt.add_raw("\n")
mt.add_param("_data_source", obbff.PREFERRED_DATA_SOURCE_FILE)
mt.add_raw("\n")
mt.add_setting("tbnews", obbff.TOOLBAR_TWEET_NEWS)
if obbff.TOOLBAR_TWEET_NEWS:
mt.add_raw("\n")
mt.add_cmd("tweetnews")
mt.add_raw("\n")
mt.add_param("_tbnu", obbff.TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES)
mt.add_param("_nttli", obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ)
mt.add_param("_tatt", obbff.TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK)
console.print(text=mt.menu_text, menu="Settings")

@log_start_end(log=logger)
Expand Down Expand Up @@ -553,3 +564,76 @@ def call_userdata(self, other_args: List[str]):
success_userdata = True

console.print()

@log_start_end(log=logger)
def call_tbnews(self, _):
"""Process tbnews command"""
if obbff.TOOLBAR_TWEET_NEWS:
console.print("Will take effect when running terminal next.")
obbff.TOOLBAR_TWEET_NEWS = not obbff.TOOLBAR_TWEET_NEWS
set_key(
obbff.USER_ENV_FILE,
"OPENBB_TOOLBAR_TWEET_NEWS",
str(obbff.TOOLBAR_TWEET_NEWS),
)

@log_start_end(log=logger)
def call_tweetnews(self, other_args: List[str]):
"""Process tweetnews command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="tweetnews",
description="Tweak tweet news parameters",
)
parser.add_argument(
"-t",
"--time",
type=check_positive,
required=False,
dest="time",
help="Time (in seconds) between tweet news updates, e.g. 300",
)
parser.add_argument(
"-a",
"--accounts",
type=str,
required=False,
dest="accounts",
help="Twitter accounts to track news separated by commmas."
"For instance: 'WatcherGuru,unusual_whales,gurgavin'",
)
parser.add_argument(
"-n",
"--number",
type=check_positive,
required=False,
dest="number",
help="Number of tweets to look into from each account, e.g. 3",
)
ns_parser = self.parse_known_args_and_warn(parser, other_args)
if ns_parser:

if ns_parser.time:
obbff.TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES = ns_parser.time
set_key(
obbff.USER_ENV_FILE,
"OPENBB_TOOLBAR_TWEET_NEWS_SECONDS_BETWEEN_UPDATES",
str(ns_parser.time),
)

if ns_parser.number:
obbff.TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ = ns_parser.number
set_key(
obbff.USER_ENV_FILE,
"OPENBB_TOOLBAR_TWEET_NEWS_NUM_LAST_TWEETS_TO_READ",
str(ns_parser.number),
)

if ns_parser.accounts:
obbff.TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK = ns_parser.accounts
set_key(
obbff.USER_ENV_FILE,
"OPENBB_TOOLBAR_TWEET_NEWS_ACCOUNTS_TO_TRACK",
str(ns_parser.accounts),
)
Loading