Search

Results include substring matches and semantically similar vals. Learn more
nbbaier avatar
aocDay4
@nbbaier
// @title Day 4 solutions
Script
return {
card: parseInt(card[0].split(" ")[1]),
numbers: card[1].split(" | ").map(side => side.split(" ")),
score: 0,
interface Card {
kj9 avatar
tweet
@kj9
An interactive, runnable TypeScript val by kj9
Script
import { TwitterApi } from "npm:twitter-api-v2";
export async function tweet(text, appKey, appSecret, accessToken, accessSecret) {
const client = new TwitterApi({
appKey,
appSecret,
accessToken,
accessSecret,
const { data: createdTweet } = await client.v2.tweet(text);
console.log("Tweet", createdTweet.id, ":", createdTweet.text);
gwoods22 avatar
sendNotification
@gwoods22
Push Notification Sender This val can be used in other vals to send notifications to a segment using OneSignal's REST API This is really handy if you want to send push notifications to your phone without building a native app! I built a barebones React PWA that asks for a password then loads the OneSignal Web SDK that I deployed to Netlify for free. OneSignal has easy to follow docs so you can build this functionality into a React, Angular, Vue app or even Wordpress! Then install the PWA on your platform of choice and you're off to the races! Setup Save your ONESIGNAL_TOKEN and SEGMENT_APPID from OneSignal to your Val Town environment variables Import into another val! import sendNotification from "https://esm.town/v/gwoods22/sendNotification";
Script
This val can be used in other vals to send notifications to a segment using [OneSignal's REST API](https://documentation.ones
otifications to your phone without building a native app! I built a barebones React PWA that asks for a password then loads t
## Setup
pomdtr avatar
tinybase_example
@pomdtr
View Example #example
Script
* @title TinyBase
* @description Automatic data synchronisation between clients using TinyBase
* @preview https://pomdtr-tinybase_example_server.web.val.run
* @include pomdtr/tinybase_example_server
* @include pomdtr/tinybase_example_client
* @resource [TinyBase Documentation](https://tinybase.org/)
ytf avatar
updateTicketCoordinator
@ytf
An interactive, runnable TypeScript val by ytf
Script
// Require the Node Slack SDK package (github.com/slackapi/node-slack-sdk)
const { WebClient, LogLevel } = import("npm:@slack/web-api");
// read all
try {
// InitializeSlack API client
const client = new WebClient(slackAccessToken, { logLevel: LogLevel.WARN });
// Fetch all users
const result = await client.users.list({ team_id: teamId });
let users = result.members;
const profiles = await Promise.all(users.map(async (user) => {
const result = await client.users.profile.get({ user: user.id });
const fields = result?.profile?.fields;
// Update target user group
await client.usergroups.users.update({
usergroup: groupId,
stevekrouse avatar
googleOauthDebug
@stevekrouse
An interactive, runnable TypeScript val by stevekrouse
Script
import { googleClient } from "https://esm.town/v/stevekrouse/googleClient";
export const googleOauthDebug = (async () => {
const client = await googleClient();
const scopes = ["https://www.googleapis.com/auth/calendar"];
const authorizationUrl = client.generateAuthUrl({
scope: scopes,
sqlite avatar
db
@sqlite
Query All Public Vals Example: val town leaderboard import { zip } from "https://esm.town/v/pomdtr/sql"; import { db } from "https://esm.town/v/sqlite/db"; const res = await db.execute("SELECT author_username, COUNT(*) AS val_count FROM vals GROUP BY author_username ORDER BY 2 DESC LIMIT 10"); console.table(zip(res));
HTTP (deprecated)
import { InStatement } from "https://esm.town/v/std/sqlite";
import type { ResultSet } from "npm:@libsql/client";
async function execute(statement: InStatement): Promise<ResultSet> {
const resp = await fetch("https://sqlite-execute.web.val.run", {
andreterron avatar
twitterRequestAccessToken
@andreterron
An interactive, runnable TypeScript val by andreterron
Script
export async function twitterRequestAccessToken(
{ code, redirect_uri, challenge, client_id, client_secret }: {
code: string;
challenge: string;
client_id: string;
client_secret: string;
const url = "https://api.twitter.com/2/oauth2/token";
"Content-Type": "application/x-www-form-urlencoded",
...basicAuthorization(client_id, client_secret),
body: body.toString(),
vtdocs avatar
uploadTextToS3
@vtdocs
Part of the Upload and download from AWS S3 guide on docs.val.town
Script
export const uploadTextToS3 = (async () => {
const { S3Client } = await import(
"https://deno.land/x/s3_lite_client@0.6.1/mod.ts"
const s3client = new S3Client({
endPoint: "s3.amazonaws.com",
secretKey: process.env.awsS3Secret,
return await s3client.putObject("filename.txt", "File contents");
robsimmons avatar
aoc_2023_10_2
@robsimmons
An interactive, runnable TypeScript val by robsimmons
Script
import { Dusa } from "https://unpkg.com/dusa@0.0.10/lib/client.js";
side RA is right :-
side RB is right :-
side LA is left :-
side LB is left :-
side B is Side :-
side A is Side,
side B is Side :-
side A is Side,
outside is Side :-
karfau avatar
test_dlock
@karfau
An interactive, runnable TypeScript val by karfau
Script
async function skip_should_reject_when_id_is_locked(
{ dlock, id, ttl, deadline, fetchStub, assertRejects, assertEquals },
const error = "lock is acquired by another client";
const err = await assertRejects(() =>
dlock({ id, ttl }, fetchStub({ error, deadline }, { status: 409 }))
jxnblk avatar
valTownBadge
@jxnblk
Add a Val Town badge to your own HTTP vals Option 1: Middleware Import the middleware from https://www.val.town/v/jxnblk/valTownBadgeMiddleware Wrap your HTML request handler with middleware, and pass import.meta.url to link to your val import wrapper from "https://esm.town/v/jxnblk/valTownBadgeMiddleware"; async function handler(req: Request): Promise<Response> { const html = ` <h1>Hello, world</h1> `; return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", }, }); } export default wrapper(handler, import.meta.url); Option 2: HTML string generator Get the HTML string for the badge using https://www.val.town/v/jxnblk/valTownBadge Add the HTML to your response's HTML string wherever you like import valTownBadge from "https://esm.town/v/jxnblk/valTownBadge"; export default async function(req: Request): Promise<Response> { const badge = valTownBadge(import.meta.url); const html = ` <h1>Hello, world</h1> ${badge} `; return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8", }, }); } Manual options You can also edit the snippet below to manually add the badge in HTML <a href="https://www.val.town/v/jxnblk/valTownBadgeExample" target="_blank" style="text-decoration:none;color:inherit"> <img src="https://jxnblk-valtownbadgesvg.web.val.run/" width="160" height="160"> </a> Or markdown: [![View source on Val Town](https://jxnblk-valtownbadgesvg.web.val.run/)](https://www.val.town/v/jxnblk/valTownBadgeExample) Vals used to create this https://www.val.town/v/jxnblk/valTownBadgeSVG SVG badge image service https://www.val.town/v/jxnblk/valTownLogotypeReact Val Town logo React component https://www.val.town/v/jxnblk/codeIconReact Code icon React component https://www.val.town/v/jxnblk/valTownBadge HTML generator that uses import.meta.url to create a link to your val https://www.val.town/v/jxnblk/valTownBadgeMiddleware Middleware to inject badge HTML in the lower right corner of your page
Script
- <https://www.val.town/v/jxnblk/valTownBadgeSVG> SVG badge image service
- <https://www.val.town/v/jxnblk/valTownLogotypeReact> Val Town logo React component
- <https://www.val.town/v/jxnblk/codeIconReact> Code icon React component
- <https://www.val.town/v/jxnblk/valTownBadge> HTML generator that uses `import.meta.url` to create a link to your val
nerdymomocat avatar
add_to_habitify_from_todoist_w_ai
@nerdymomocat
// if you added new items to habitify after running this script
Cron
apiKey: OPENAI_API_KEY ?? undefined,
const client = Instructor({
client: oai,
mode: "TOOLS",
if (!date.includes("T")) {
date = date + "T23:00:00"; // if no time is included, consider it completed at 11pm
const parsedDate = Date.parse(date);
const sys_prompt = createPrompt(habitKeys.join(), specialPrompt);
const processed_message = await client.chat.completions.create({
messages: [
joey avatar
BlobArray
@joey
Blob Array Create an array as a Database, instantly! Just create a new val for your array: import { BlobArray } from "https://esm.town/v/joey/BlobArray"; type User = { email: string }; // specify the type inside the TS generic <> to define the type of your array export let myUserArray = BlobArray<User>("my-user-array"); Now import it and start using it in your vals! import { myUserArray } from "https://esm.town/v/joey/myUserArray"; // overwrite the entire array await myUserArray.set([{ email: "user1@gmail.com" }, { email: "user2@yahoo.com" }]); // get all the entries in your array const allUsers = await myUserArray.get(); // call any array method you want, just use "await" await myUserArray.push({ email: "johndoe@gmail.com" }); const gmailUsers = await myUserArray.filter(u => u.email.includes("@gmail.com"));
Script
type User = { email: string };
// specify the type inside the TS generic <> to define the type of your array
export let myUserArray = BlobArray<User>("my-user-array");
madhatter349 avatar
umbrellaReminder
@madhatter349
ā˜”ļø Umbrella reminder if there's rain today Setup Fork this val šŸ‘‰ https://val.town/v/stevekrouse.umbrellaReminder/fork Customize the location (line 8). You can supply any free-form description of a location. āš ļø Only works for US-based locations (where weather.gov covers). How it works Geocodes an free-form description of a location to latitude and longitude ā€“ @stevekrouse.nominatimSearch Converts a latitude and longitude to weather.gov grid ā€“ @stevekrouse.weatherGovGrid Gets the hourly forecast for that grid Filters the forecast for periods that are today and >30% chance of rain If there are any, it formats them appropriately, and sends me an email
Cron
export const umbrellaReminder = async (arg) => {
if (arg.method) return Response.json("");
let location = "Upper West Side, New York"; // <---- customize this line
let [{ lat, lon }] = await nominatimSearch({
q: location,