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

Updating Dependencies & Resurrecting MetaGame's Discord Bot #1759

Draft
wants to merge 3 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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: 1 addition & 1 deletion .node-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
20
22.3.0
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
lts/gallium
lts/iron
13 changes: 5 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
],
"devDependencies": {
"@apollo/rover": "^0.18.0",
"@composedb/cli": "^0.4.4",
"@composedb/cli": "^0.7.1",
"@graphql-codegen/add": "^5.0.0",
"@graphql-codegen/cli": "^5.0.0",
"@graphql-codegen/introspection": "^4.0.0",
Expand All @@ -63,11 +63,13 @@
"@graphql-codegen/typescript-react-apollo": "^3.3.7",
"@graphql-codegen/typescript-resolvers": "^4.0.1",
"@graphql-codegen/typescript-urql": "^4.0.0",
"@types/create-hash": "^1.2.6",
"@types/jest": "^29.2.1",
"@types/node": "^20.8.6",
"@types/node-fetch": "^2.6.2",
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"@types/secp256k1": "^4.0.6",
"@types/uuid": "8.3.4",
"@typescript-eslint/eslint-plugin": "5.45.0",
"@typescript-eslint/parser": "^6.6.0",
Expand All @@ -93,17 +95,12 @@
"prettier": "2.7.1",
"standard-version": "9.3.2",
"ts-jest": "^29.0.3",
"typescript": "^5.0.0",
"typescript": "^5.5.2",
"wait-on": "6.0.1"
},
"resolutions": {
"@ceramicnetwork/common": "2.31.1",
"did-resolver": "4.1.0",
"dids": "4.0.4",
"graphql": "16.5.0",
"graphql": "16.9.0",
"multihashes": "4.0.3",
"node-gyp": "10.0.1",
"better-sqlite3": "9.4.5",
"nan": "2.18.0"
},
"browserslist": [
Expand Down
66 changes: 33 additions & 33 deletions packages/backend/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,39 +58,39 @@ const config = {
typesPrefix: 'DaoHaus',
},
},
'src/lib/autogen/seedgraph-sdk.ts': {
schema: 'https://api.thegraph.com/subgraphs/name/tenfinney/polygon-seeds',
documents: [
'src/handlers/remote-schemas/resolvers/seedGraph/**/(!(*.d)).ts',
],
plugins: [
'typescript',
'typescript-operations',
'typescript-graphql-request',
{ add: { content: '/* eslint-disable */' } },
],
config: {
avoidOptionals: true,
dedupeOperationSuffix: true,
},
},
'src/lib/autogen/balancerpolygon-sdk.ts': {
schema:
'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-polygon-v2',
documents: [
'src/handlers/remote-schemas/resolvers/balancerPolygon/**/(!(*.d)).ts',
],
plugins: [
'typescript',
'typescript-operations',
'typescript-graphql-request',
{ add: { content: '/* eslint-disable */' } },
],
config: {
avoidOptionals: true,
dedupeOperationSuffix: true,
},
},
// 'src/lib/autogen/seedgraph-sdk.ts': {
// schema: 'https://api.thegraph.com/subgraphs/name/tenfinney/polygon-seeds',
// documents: [
// 'src/handlers/remote-schemas/resolvers/seedGraph/**/(!(*.d)).ts',
// ],
// plugins: [
// 'typescript',
// 'typescript-operations',
// 'typescript-graphql-request',
// { add: { content: '/* eslint-disable */' } },
// ],
// config: {
// avoidOptionals: true,
// dedupeOperationSuffix: true,
// },
// },
// 'src/lib/autogen/balancerpolygon-sdk.ts': {
// schema:
// 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-polygon-v2',
// documents: [
// 'src/handlers/remote-schemas/resolvers/balancerPolygon/**/(!(*.d)).ts',
// ],
// plugins: [
// 'typescript',
// 'typescript-operations',
// 'typescript-graphql-request',
// { add: { content: '/* eslint-disable */' } },
// ],
// config: {
// avoidOptionals: true,
// dedupeOperationSuffix: true,
// },
// },
},
};

Expand Down
18 changes: 7 additions & 11 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,22 @@
"test": "jest --passWithNoTests"
},
"dependencies": {
"@ceramicnetwork/stream-caip10-link": "^2.26.1",
"@composedb/client": "^0.4.4",
"@ceramicnetwork/stream-caip10-link": "^5.14.0",
"@composedb/client": "^0.7.1",
"@graphql-tools/schema": "8.3.2",
"@metafam/discord-bot": "0.1.0",
"@metafam/utils": "1.0.1",
"bluebird": "3.7.2",
"bottleneck": "^2.19.5",
"cors": "2.8.5",
"discord.js": "13.6.0",
"discord.js": "^14.15.3",
"dotenv": "16.0.0",
"ethers": "5.7.2",
"express": "^4.18.2",
"express-graphql": "0.12.0",
"graphql": "16.5.0",
"graphql-request": "4.0.0",
"graphql-tag": "2.12.6",
"express-graphql": "^0.12.0",
"graphql": "^16.9.0",
"graphql-request": "^7.1.0",
"graphql-tag": "^2.12.6",
"showdown": "^2.1.0",
"uuid": "8.3.2"
},
Expand All @@ -48,10 +48,6 @@
"nodemon": "^2.0.20",
"ts-node": "^10.9.1"
},
"resolutions": {
"better-sqlite3": "9.4.5",
"node-gyp": "10.0.1"
},
"nodemonConfig": {
"exec": "node --inspect=0.0.0.0:4322 --loader ts-node/esm src/index.ts",
"watch": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default async (req: Request, res: Response): Promise<void> => {
});
const modelInstanceDoc = await composeDBClient.context.loadDoc(nodeId);

if (!modelInstanceDoc) throw new Error('`modelInstanceDoc` not defined.');
const { controller } = modelInstanceDoc.metadata;

// There is probably a better way to do this...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export const updatePlayerFromComposeDB = async (
try {
({ did } = await Caip10Link.fromAccount(
composeDBClient.context.ceramic,
// mainnet; the site prompts them to switch if necessary
// optimism; the site prompts them to switch if necessary
`${ethereumAddress.toLowerCase()}@eip155:10`,
));

Expand Down
11 changes: 6 additions & 5 deletions packages/backend/src/handlers/auth-webhook/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const authHandler = async (
): Promise<void> => {
try {
const token = getHeaderToken(req);
console.info(`Token for request: ${token}.`);
if (!token) {
res.json(unauthorizedVariables);
return;
Expand All @@ -42,11 +43,11 @@ export const authHandler = async (
const { limiter } = req.app.locals;
const { id, created } = await getOrCreatePlayerId(claim.iss, limiter);

if (created) {
console.debug(
`Created and Authorized playerId: ${id} with address: ${claim.iss}`,
);
}
console.info(
`${
created ? 'Created and ' : ''
}Authorized playerId: ${id} with address: ${claim.iss}`,
);

const hasuraVariables = {
'X-Hasura-Role': 'player',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createDiscordClient } from '@metafam/discord-bot';
import { GuildBasedChannel, Role, TextChannel } from 'discord.js';
import { ChannelType, GuildBasedChannel, PermissionFlagsBits, Role, TextChannel } from 'discord.js';
import showdown from 'showdown';

import { client } from '../../../../lib/hasuraClient.js';
Expand All @@ -16,11 +16,9 @@ export const getGuildDiscordRoles: QueryResolvers['getGuildDiscordRoles'] =

if (discordGuild != null) {
await discordGuild.roles.fetch();
return discordGuild.roles.cache.map((role: Role) => ({
id: role.id,
position: role.position,
name: role.name,
}));
return discordGuild.roles.cache.map(
({ id, position, name }) => ({ id, position, name })
)
}

return [];
Expand Down Expand Up @@ -52,11 +50,9 @@ export const getDiscordServerMemberRoles: QueryResolvers['getDiscordServerMember

// these are returned in descending order by position
// (meaning, most significant role is first)
return member.roles.cache.map((role: Role) => ({
id: role.id,
position: role.position,
name: role.name,
}));
return member.roles.cache.map(
({ id, position, name }) => ({ id, position, name })
);
}
} catch (err) {
console.error({ err });
Expand All @@ -76,15 +72,15 @@ export const getGuildDiscordAnnouncements: QueryResolvers['getGuildDiscordAnnoun
// It also seems to be necessary to populate the "channels" cache used below
await discordGuild.members.fetch();
const viewChannelPerm =
discordGuild.me?.permissions.has('VIEW_CHANNEL');
discordGuild.members.me?.permissions.has(PermissionFlagsBits.ViewChannel);
if (!viewChannelPerm) {
console.warn(
`Guild (id=${guildDiscordId}) does not have the VIEW_CHANNEL permission, skipping announcement fetching...`,
);
return [];
}
const newsChannels = discordGuild.channels.cache.filter(
(channel: GuildBasedChannel) => channel.type === 'GUILD_NEWS',
({ type }) => type === ChannelType.GuildAnnouncement,
);

if (newsChannels.size > 0) {
Expand All @@ -94,9 +90,11 @@ export const getGuildDiscordAnnouncements: QueryResolvers['getGuildDiscordAnnoun
if (messages == null) {
return [];
}
return messages
return (
messages
.sorted((m1, m2) => m2.createdTimestamp - m1.createdTimestamp)
.first(10);
.first(10)
);
}),
);

Expand All @@ -116,8 +114,8 @@ export const getGuildDiscordAnnouncements: QueryResolvers['getGuildDiscordAnnoun
.map((message) => markdownConverter.makeHtml(message.cleanContent));
}
}
} catch (e) {
console.error(e);
} catch (error) {
console.error({ error });
}
return [];
};
11 changes: 8 additions & 3 deletions packages/discord-bot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@

Run `yarn dev`.

## Docker Commands
## Local Docker

To build: from the repository root: `docker build -f docker/discord-bot/Dockerfile -t discord-bot .`
To build: from the repository root: `yarn docker:build`

To run: `docker run discord-bot`
To run: `docker run gcr.io/metagame-thegame/discord-bot:latest`

## Delopying to Google’s Cloud Run

1. `docker push gcr.io/metagame-thegame/discord-bot:latest`
2. Set up a Cloud Run instance & select the image from the Container Registry.
17 changes: 7 additions & 10 deletions packages/discord-bot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,25 @@
"precommit": "yarn typecheck",
"generate": "graphql-code-generator",
"fix:lint": "eslint --fix",
"test": "jest --passWithNoTests"
"test": "jest --passWithNoTests",
"docker:build": "docker buildx build --tag gcr.io/metagame-thegame/discord-bot:latest --file ../../docker/discord-bot/Dockerfile ../../"
},
"dependencies": {
"@discordx/importer": "1.1.2",
"@metafam/utils": "1.0.1",
"@types/node": "18",
"@types/node-fetch": "2.5.10",
"discord.js": "13.6.0",
"discordx": "9.1.12",
"discord.js": "^14.15.3",
"dotenv": "16.0.0",
"ethers": "5.6.9",
"express": "4.17.3",
"graphql": "16.5.0",
"graphql": "^16.9.0",
"graphql-request": "^6.1.0",
"graphql-tag": "2.12.6",
"node-fetch": "3.2.1",
"reflect-metadata": "0.1.13",
"sourcecred": "0.11.0"
"reflect-metadata": "0.1.13"
},
"devDependencies": {
"@types/express": "^4.17.14",
"nodemon": "^2.0.20"
"nodemon": "^2.0.20",
"typescript": "^5.5.2"
},
"nodemonConfig": {
"exec": "node --inspect=0.0.0.0:4323 --loader ts-node/esm src/start.ts",
Expand Down
16 changes: 6 additions & 10 deletions packages/discord-bot/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,20 @@ import {
OAuth2CodeExchangeResponse,
} from './types.js';

export const tokenRequestData = {
const tokenRequestData = {
client_id: Constants.DISCORD_BOT_CLIENT_ID,
client_secret: CONFIG.discordBotClientSecret,
client_secret: CONFIG.botSecret,
grant_type: 'authorization_code',
redirect_uri: `${CONFIG.frontendUrl}/${Constants.DISCORD_OAUTH_CALLBACK_PATH}`,
redirect_uri: `${CONFIG.frontendURL}/${Constants.DISCORD_OAUTH_CALLBACK_PATH}`,
};

export const exchangeCodeForAccessToken = async (
code: string,
): Promise<DiscordAccessTokenResponse> => {
const data = {
...tokenRequestData,
code,
};
const data = { ...tokenRequestData, code };

const discordResponse = await fetch(
`${CONFIG.discordApiBaseUrl}/oauth2/token`,
`${CONFIG.discordAPIBaseURL}/oauth2/token`,
{
method: 'POST',
body: new URLSearchParams(data),
Expand All @@ -37,9 +34,8 @@ export const exchangeCodeForAccessToken = async (
};

if (discordResponse.ok) {
const parsedBody =
response.oauthResponse =
(await discordResponse.json()) as OAuth2CodeExchangeResponse;
response.oauthResponse = parsedBody;
} else {
response.error = discordResponse.statusText;
}
Expand Down
Loading
Loading